VC++ Precompiled Headers
Jul 16, 2015

I have a huge C++ project that takes over a minute to compile in Debug and Release mode. I use the /MP flag to use all available processors to compile the project, and it still takes over a minute to recompile.

I also modify header files a lot so that just makes the entire project recompile which is very annoying and takes a long time.

Precompiled headers mitigate this issue by compiling all of your headers a single time, instead of compiling each header for each .cpp file.

This probably isn’t worth the effort if your project is fairly small though.

  1. So, to get started you first need to create new “stdafx.cpp” and “stdafx.h” files and add them to your projects base.

  2. Your project should be set to “Not Using Precompiled Headers”.

  3. Right click on “stdafx.cpp” -> Properties -> C/C++ -> Precompiled Headers -> Precompiled Header -> Create (/Yc) -> OK

  4. Select every .cpp file in your project and right click -> Properties -> C/C++ -> Precompiled Headers -> Precompiled Header -> Use (/Yu) -> OK

  5. Now go through every .cpp and .h file and put all the includes in “stdafx.h”. Now go back through and delete all the includes.

  6. Edit every .cpp file and add #include “stdafx.h” to the top, including your new “stdafx.cpp” file, and it must be exactly #include “stdafx.h” and not an exact path like “../../stdafx.h”. Header files should have 0 includes in them.

  7. Add these includes to the top of your “stdafx.h”. These two files are used by the compiler to target a specific version of Windows. Without them you could end up calling functions that don’t exist on previous versions of Windows. Such as GetTickCount64 and GetProductInfo.

#include "WinSDKVer.h"
#include "SDKDDKVer.h"
  1. The order of the includes inside your “stdafx.h” file matter, so you’ll need to mess around with the order until you get a successful compile.

  2. Once you get a successful compile, you should see it stop on “stdafx.cpp” for a couple seconds then a massive speed up once it starts processing the .cpp files.

  3. Now repeat steps 2 - 4 in your other project modes (Debug/Release).

For one of my projects I was able to cut down a complete rebuild from 1:13 to 0:17 in Debug mode. It’s that amazing.

Comments