Precompiled headers with GCC

I have definitely had success. First, I used the following code:

#include <boost/xpressive/xpressive.hpp>
#include <iostream>

using namespace std;
using namespace boost::xpressive;

// A simple regular expression test
int main()
{
    std::string hello("Hello, World!");

    sregex rex = sregex::compile( "(\\w+) (\\w+)!" );
    smatch what;

    if( regex_match( hello, what, rex ) )
    {
        std::cout << what[0] << '\n'; // Whole match
        std::cout << what[1] << '\n'; // First capture
        std::cout << what[2] << '\n'; // Second capture
    }
    return 0;
}

This was just a Hello, World! program from Boost Xpressive. First, I compiled with the -H option in GCC. It showed an enormous list of headers that it used. Then, I took a look at the compile flags my IDE (Code::Blocks) was producing and saw something like this:

g++ -Wall -fexceptions  -g  -c main.cpp -o obj/Debug/main.o

So I wrote a command to compile the Xpressive.hpp file with the exact same flags:

sudo g++ -Wall -fexceptions  -g /usr/local/include/boost/xpressive/xpressive.hpp

I compiled the original code again with the -H and got this output:

g++ -Wall -fexceptions -H  -g     -c main.cpp -o obj/Debug/main.o

! /usr/local/include/boost/xpressive/xpressive.hpp.gch
main.cpp
. /usr/include/c++/4.4/iostream
.. /usr/include/c++/4.4/x86_64-linux-gnu/bits/c++config.h
.. /usr/include/c++/4.4/ostream
.. /usr/include/c++/4.4/istream
main.cpp

The ! means that the compiler was able to use the precompiled header. An x means it was not able to use it. Using the appropriate compiler flags is crucial. I took off the -H and ran some speed tests. The precompiled header had an improvement from 14 seconds to 11 seconds. Not bad, but not great.

Note: Here’s the example. I couldn’t get it to work in the post.

BTW: I’m using the following g++:

g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3

Leave a Comment