Short story:
I can't make precompiled headers work properly with gcc -c option.
Long story:
Folks, I'm using gcc-4.4.1 on Linux and before trying precompiled headers in a really large project I decided to test them on simple program. They "kinda work" but I'm not happy with results and I'm sure there is something wrong about my setup.
First of all, I wrote a simple program(main.cpp) to test if they work at all:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/type_traits.hpp>
int main()
{
return 0;
}
Then I created the precompiled headers file pre.h(in the same directory) as follows:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/type_traits.hpp>
...and compiled it:
$ g++ -I. pre.h
(pre.h.gch was created)
After that I measured compile time with and without precompiled headers:
with pch
$ time g++ -I. -include pre.h main.cpp
real 0m0.128s
user 0m0.088s
sys 0m0.048s
without pch
$ time g++ -I. main.cpp
real 0m0.838s
user 0m0.784s
sys 0m0.056s
So far so good! Almost 7 times faster, that's impressive! Now let's try something more realistic. All my sources are built with -c option and for some reason I can't make pch play nicely with it. You can reproduce this with the following steps below...
I created the test module foo.cpp as follows:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/type_traits.hpp>
int whatever()
{
return 0;
}
Here are the timings of my attempts to build the module foo.cpp with and without pch:
with pch
$ time g++ -I. -include pre.h -c foo.cpp
real 0m0.357s
user 0m0.348s
sys 0m0.012s
without pch
$ time g++ -I. -c foo.cpp
real 0m0.330s
user 0m0.292s
sys 0m0.044s
That's quite strange, looks like there is no speed up at all!(I ran timings for several times). It turned out precompiled headers were not used at all in this case, I checked it with -H option(output of "g++ -I. -include pre.h -c foo.cpp -H" didn't list pre.h.gch at all).
What am I doing wrong?
Ok, I think I've found the solution: -fpch-preprocess should be used alongside with -c option. It works like a charm!
Here's the timings:
with pch
$ time g++ -I. -include pre.h -c foo.cpp -fpch-preprocess
real 0m0.028s
user 0m0.016s
sys 0m0.016s
without pch
$ time g++ -I. -c foo.cpp
real 0m0.330s
user 0m0.292s
sys 0m0.044s
Update: I asked the same question on the gcc help mailing list and Ian Lance Taylor explained this strange behavior by my usage of distcc/ccache. These tools first preprocess the source that's why this options is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With