Friday, May 27, 2022

A (better) explanation of (a part of) precompiled headers

 I've  searched for a long time for an explanation of precompiled headers in Visual Studio projects. A precompiled header can speed up compilation times. There is much about this on the Interweb. But not much about what I explain here.

 Precompiled headers are usually setup automatically by Visual Studio when you start a new C++ project, and you need not touch them much. But sometimes you need to change your project in some way and the precompiled headers just seem to get, er, what? Confused? Confusing. So here is what I have learned recently.

 They used to be "handled" by stdafx.h and stdafx.cpp but now are "handled" by pch.h and pch.cpp. As far as I can see this is just a name change.

 You add (much used but hardly ever changed) include files inside pch.h (or stdafx.h).

Now here is something I did not realize: You actually set the compilation properties of the individual CPP file to get the precompiled headers working. pch.cpp (or stdafx.cpp) is given the property of creating the precompiled header...


...and all the other files in your project are given the property of using the precompiled header...

When you do this you'll notice that if the precompiled header files need recreating, when you compile pch.cpp or stdaxf.cpp will get compiled first.

pch.cpp is usually an almost empty file with just the include of the h file:

#include "pch.h"

I hope this helps you...good luck!