stdafx.h

Hi,

Does the program becomes heavier and slower if I include "stdafx.h" in every header and source file?
C++ guarantees a simple foundational rule: "You don't pay for what you don't use". At runtime, you can include all the header files in the world, but as long as they're only header files they'll have no impact on performance.

Compilation time will suffer, though, (much) less so if the header is precompiled.

Stdafx.h is generated by the IDE to speed up compilation, since it's pre-compiled. If it doesn't change, the compiler is fed a faster-to-process file instead of that.

If there are a lot of large header-file dependencies, this can speed up compilation. Don't include what you don't need, and try to limit includes in header files to just what is required for interfaces. Put the include statements required for the implementation code in the source file. This stops any other TU that includes the header from including all the dependencies required for the implementation of that other TU.
Ok, I see. Although I feel I didn't quite get it all the way through:

If I include stdafx.h in my source files, and only a few headers in my header files like <vector> <iostream> etc, wouldn't these be compiled twice because they aren't part of the precompiled header?

In other words, if I use two headers twice, isn't it considered to be twice as much code in my program?
if I use two headers twice, isn't it considered to be twice as much code in my program?

If the same header is included twice, only one copy of the contents of the header is inserted by the preprocessor thanks to the macro guards (or the corresponding pragma), per translation unit.

If those two headers are both included in two different translation units, yeah - the compiler's handling the same header-file contents twice, across different invocations of the compiler.

If you're using a precompiled header, compilation speed might decrease, because if a common header is precompiled the PCH can be used instead of the source code, saving work in all the translation units that use it.

Just to make it explicit, none of this has any effect on space/time performance of your program - we're talking only about compilation speed here.
Last edited on
Topic archived. No new replies allowed.