Jona
Jona

Reputation: 719

Pre-compiled header is not used when including standard library

I'm trying to create a pre-compiled header and use it when compiling a cpp file. I have the 2 following files:
main.cpp:

#include "foo.hpp"

int main()
{
    myTemplate<int> obj;

    return 0;
}

and foo.hpp:

#ifndef FOO_HPP
#define FOO_HPP

template<class T>
class myTemplate
{
};

#endif

I'm running this command to create a gch file

g++ -std=c++11 foo.hpp

Then I'm making the object file, using the -H flag to see what files are being used

g++ -std=c++11 -H -c main.cpp

and the output is

! foo.hpp.gch
 main.cpp

Good. The gch file is being used.

Now I insert this line at the beginning of main.cpp

#include <iostream>

Now when I'm trying to create the object file, with the same command as before, I get a long list of files (most of them are from the standard library of course) but none of them is foo.hpp.gch. I do see foo.hpp in the list.
Why does it make a difference?
How can I use a pre-compiled header when making an object file, when the header includes the standard library?

Upvotes: 1

Views: 395

Answers (1)

Anedar
Anedar

Reputation: 4265

As requested, here my comment as an answer:

Include the precompiled header first and then the standard library.

This behaviour is probably, because the compiler can not know if the not-precompiled header (here the standard library) changes e.g. some macro definitions that influence the precompiled header and make it invalid. (Maybe someone could verify this, since it's only a guess)

Upvotes: 1

Related Questions