I was having troubles getting pre-compiled headers to work, so I came up with the following minimal-working-example.
This is the header file foo.h
#include <iostream>
using namespace std;
void hello() {
cout << "Hello World" << endl;
}
I compile this as g++ -c foo.h
gives me a compiled header foo.gch
. I expect that when I compile the following source file that includes foo.h
, it should pick the header foo.h.gch
and I am good.
// test.cpp
#include <cstdio> // Swap ordering later
#include "foo.h" // ------------------
int main() {
hello();
}
But surprisingly, this does not compile using foo.h.gch
, but rather uses foo.h
. To verify you can compile this as g++ -H test.cpp
However, if I change the order of included header files as follows:
// test.cpp
#include "foo.h" // ------------------
#include <cstdio> // Ordering swapped
int main() {
hello();
}
Now if I compile using g++ -H test.cpp
, it compiles from foo.h.gch
, whew!
So I was wondering if this is a bug in GCC or are we supposed to use pre-compiled headers like that? In either case I think its useful to know..
With GCC, precompiled headers work only if they are the only header, and if they are included first (without any previous header).
This answer explains more why it is so. See also the Precompiled headers chapter of GCC documentation, which says:
- Only one precompiled header can be used in a particular compilation.
- A precompiled header can't be used once the first C token is seen.
BTW, it could happen that pre-compiling some large header (notably in C++) is not worth the effort. YMMV.
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