Configuring your compiler: Precompiled headers


As noted in a prior lesson, the compiler works by compiling each code file individually. So in a project with three code files (which we’ll call a.cpp, b.cpp, and c.cpp), the compiler will compile a.cpp, b.cpp, and c.cpp separately (the specific order of compilation is determined by the IDE, and shouldn’t matter).

Each code file may optionally contain one or more references to other files. Let’s say that a.cpp, b.cpp, and c.cpp each contain a reference to a file called
d.h. When a.cpp gets compiled, the contents of d.h will get compiled too. Then when b.cpp gets compiled, the contents of d.h will get compiled again. d.h will get compiled as many times as it is referenced by other code files!

Since d.h doesn’t change between each compilation, this recompilation is wasteful.

Precompiled headers

Precompiled headers is a technique that can be employed so that files like d.h would only be compiled once regardless of how many times it’s referenced.

For large programs (e.g. those with hundreds of files), precompiled headers can significantly reduce the amount of time it takes to compile a program. For short programs, precompiled header provides only marginal benefit.

Because precompiled headers provide little benefit for smaller programs, and because they add complexity, we advise turning them off.

Best practice

If you’re using Visual Studio, turn off precompiled headers before writing your programs. The performance increase is minimal, and the added complexity isn’t worth it.

For Visual Studio users

To turn precompiled headers off, right click on your project name in the Solution Explorer window, then choose Properties:

From the properties dialog, select C/C++ > Precompiled Headers, and set the Precompiled Header option to Not Using Precompiled Headers.

Once that’s done, at the top of your main .cpp file, you can remove either of the following two lines (if they exist) as they are now extraneous:

For other compilers

Other compilers should not need to do anything, as precompiled headers are generally turned off by default.