Why does Visual Studio C ++ require the inclusion of & ldquo; StdAfx.h & rdquo; even on files that do not need it?


I understand what precompiled headers are doing with "#include "StdAfx.h" and yes, I know I can turn them off. But that's not my question.

If you're using precompiled headers, Visual C++ requires every cpp file to #include "StdAfx.h", even the files that aren't using any of the headers in StdAfx.h. If you forget to include StdAfx.h on one file, it's an error. But why? The obvious approach would be just "If you include StdAfx.h then that file will use it, but if you forget to include it, then those header files will simply not be included." I don't understand why VC++ would require you to include StdAfx.h when it's not needed. Seems like it would have been easier for them to treat it like a normal header file.

Is there any good reason why this is required?

Your project default is "use precompiled headers". You can set individual files to "not use precompiled headers" if you desire.

In fact, stdafx.cpp itself has a different option from the project defaults:

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

The project defaults are:

What this configuration is saying is "For each compiled file, start with the precompiled data in the specified .pch and start compiling new information after the point stdafx.h is included." That's important and why stdafx.h should be included as the first line of the file. It will still work if you put it later in the file, but anything before the #include is ignored because that data won't be in the .pch. Absence of the #include means VS will scan the whole file looking for the pre-compiled starting location and not find it...generating an error.

If you have a file that you don't want to use pre-compiled information, you can select the file and override it. Example:

Visual Studio won't use the precompiled information and won't look for a header to include.