Precompiled headers

From Code::Blocks

Using precompiled headers (or PCH) speeds up the compilation of large projects (like Code::Blocks itself) by large amounts. This works by creating a header file which #includes all the rarely-changing header files for your project. Then the compiler is instructed to pre-compile this header file. This creates a new file which is now in a binary format that only the compiler understands. But, since it doesn't have to re-parse your header files for every source file that includes them, the process will now be considerably faster.

Creating a precompiled header

To create a precompiled header for your project, just create a new header file. Say you named it "pch.h". Put the following in it:


// #include your rarely changing headers here


replacing PUT_A_UNIQUE_NAME_HERE with something unique. Also #include your rarely-changing headers in that file, e.g.


#if ( !defined(WX_PRECOMP) )
    #define WX_PRECOMP

// basic wxWidgets headers
#include <wx/wxprec.h>

#ifndef WX_PRECOMP
	#include <wx/wx.h>

// #include other rarely changing headers here


Marking a header for precompilation

Now this file is ready to be marked as PCH. To do this, find the file in the ProjectManager tree, right-click on it and select "Properties".


Click "Compile file" and make sure it's checked.

Do not click "Link file".

Also, set the priority weight to zero, to force it to be compiled before all other files (default priority is 50 - the lower this number, the higher the priority). Exit this dialog by clicking "OK".

Using a precompiled header

You 're almost there. Only thing left is to actually include this file so that it can be used. There are two ways to do this.

  1. Include it in every source file of your project (_not_ header files, only source files like *.cpp). This *must* be the very first C token in the file. In other words, put it really first. Only comments are harmless before it.
  2. Go to "Project->Build options" and add the following in "Compiler->Other options":
-include "pch.h"

The first line will emit a warning when building your project, if the PCH is _not_ used. It's nice to know this.

The second line, does all the magic: it's like adding #include "pch.h" at the top of each of your source files, except you don't have to edit them.

This doesn't work in all situations, but it's the quick way to add PCH in your project. Specifically, it won't work if the PCH is in the same directory as the project file. If that's the case, go to "Project->Properties" and set the PCH mode to "Generate PCH in a directory alongside the original file" (first option).