Why does Visual Studio C ++ require the inclusion of "StdAfx.h" even in files that it does not need?

I understand what precompiled headers do with "#include" StdAfx.h ", and yes, I know I can disable them. But that is not my question.

If you use precompiled headers, Visual C ++ requires that each cpp file contains #include "StdAfx.h", even files that do not use any of the headers in StdAfx.h. If you forgot to include StdAfx.h in one file, this is an error. But why? The obvious approach would be simply "If you enable StdAfx.h, this file will use it, but if you forget to include it, then these header files will simply not be included." I do not understand why VC ++ will require you to include StdAfx.h when it was not necessary. It seems like it would be easier for them to consider it as a regular header file.

Is there a good reason why this is required?

+5
source share
2 answers

By default, your project uses "using precompiled headers." You can set individual files to "do not use precompiled headers" if you wish.

In fact, stdafx.cpp itself is different from the default options:

enter image description here

What this configuration says is β€œstart compiling this file (stdafx.cpp), stop when you finish compiling the statement that includes stdafx.h”, and save the precompiled information as a .pch file. "Visual studio is also smart enough to first compile this file so that it is available for use.

Project defaults:

enter image description here

This configuration says: "For each compiled file, start with the precompiled data in the specified .pch and start compiling new information after you include the stdafx.h point." This is important and why stdafx.h should be included in the first line of the file. It will still work if you put it later in the file, but nothing but #include is ignored because this data will not be in .pch. The absence of the #include means that VS scans the entire file looking for a precompiled source location, but does not detect it ... generates an error.

If you have a file that you do not want to use precompiled information, you can select the file and override it. Example:

enter image description here

Visual Studio will not use precompiled information and will not search for a title to include.

+7
source

Just adding Marks answer. In fact, you do not need to manually include stdafx.h in all project source files. You can use the Forced Include Files project option: enter image description here

Thus, stdafx.h will be automatically included in all your sources.

+7
source

Source: https://habr.com/ru/post/1262964/


All Articles