Precompiled Headers in Header Files

irwinb picture irwinb · Jul 9, 2012 · Viewed 12.1k times · Source

I ran into precompiled headers today for the first time..forever changing my life. I can't believe compiling my C++ code could be that fast. It makes total sense now..

Anyway, one thing that is confusing me is that from what I've read so far, pre-compiled headers only should be added to source files( cpp? ).

In Visual Studio, there is an option under Project Properties->C/C++->Advanced to "Force Include File". I set that compiler option to stdafx.h.

After doing this..I no longer require to include the headers I have added to my stdafx.h, even inside my header files ( source files are supposed to automatically include stdafx.h ). Is this expected behaviour?

I can't find a place that's clear in the distinction between header/source files.

If it does..great but I'm afraid it's another one of those things VC++ lets you get away with but will break in GCC. And yes..it needs to be portable; at least between GCC and VC++.

Answer

syplex picture syplex · Jul 9, 2012

StdAfx.h really should only be included in source files, not headers. I would suggest you #include "StdAfx.h" first in every cpp and not use the "Force Include File" option. Thats how I do it with my cross-platform projects. For the record, I don't actually use precompiled headers in GCC I just build it normally and it works well.

For some background. The compiler only looks at source files (ie, *.cpp, *.c, etc) and so when it compiles them it has to include every header and compile any code found in the headers as well. The precompiled headers option allows for compiling all of that code (ie, the globally include'd code in StdAfx.h) once so that you don't have to do it all of the time. Thats what StdAfx.cpp is for. The compiler compiles StdAfx.cpp with all of the code included in StdAfx.h once instead of having to do it every time you build.

So, since you include StdAfx.h in every source file as the first item, it doesn't make sense to include it in any of the headers since they will be included AFTER StdAfx.h and thus will have access to all of the code in StdAfx.h. Plus you can then use those headers in other projects without having to worry about having a StdAfx.h around or including the wrong one.