Precompiled headers - GCC

February 26th, 2007

Some time ago I started using precompiled headers in my Windows projects. Having so many includes caused that compilation was taking too much time. Precompiled headers are really helpful in this case.
I will show you how to use them with gcc compiler.

Let's say that we have a few cpp files which use some headers - for example string, vector, iostream.

main.cpp

C++:
#include "foo.h"
int main()
{
    Foo f;
    f.Test("Hello PCH World");
    return 0;
}

foo.h

C++:
#include <string>
#include <vector>
class Foo
{
        private:
        std::vector<int> something;
        public:
        Foo();
        ~Foo();
        void Test(const std::string &txt);
};

foo.cpp

C++:
#include "foo.h"
#include <iostream>
using namespace std;
Foo::Foo()
{
}
Foo::~Foo()
{
}
void Foo::Test(const string &txt)
{
    cout <<txt.c_str() <<endl;
}

Any time when compiler deals with cpp files it must compile all headers they include. If there are too many of them, compilation time can be very long. So it is a good idea to put all common headers in one file - put there ones that will not change anymore (like common libraries headers). When you choose right files it is a time to precompile our header. I saved it as precomp.h.

C++:
#include <iostream>
#include <string>
// include more if you need

Now, the most important thing. Name of our precompiled header must be the same as a header with .gch suffix. Any time gcc needs to include a header it looks for a file headername.h.gch. When one exists compiler uses it.

So precompile the header:

g++ -xc++-header precomp.h -o precomp.h.gch

Now we need to make some changes in our code. Use #include "precomp.h" in every source file and delete includes which we've just moved to a precompiled header. That's all.

Are you curious what impact precompiled headers have on the building time? I am writing a jabber client (about 30 files right now using external libraries like Expat and wxWidgets). Normally it compiles in about 1 minute and 40 seconds. When I put all common headers in one file and precompiled it, time of compilation was reduced to only 30 seconds! Really worth a shot.

Leave a Reply

Designed by SirMike © All rights reserved

Valid XHTML 1.0! Valid CSS!