Soapy
Soapy

Reputation: 567

Can Precompiled Headers Be Used Like Libraries?

Is it possible to use Precompiled Headers like a library is used? For example can I create a header containing preprocessor like so:

#include <iostream>
#include <string>
#include "boost_headers.hpp"

Compile it into a PCH and then distribute the PCH without having to distribute the headers files used to create it?

Upvotes: 3

Views: 1128

Answers (2)

Sebastian Redl
Sebastian Redl

Reputation: 71969

No. Precompiled headers have multiple aspects that make them unsuitable as a distribution format.

  • They're unstable. Any change to the compiler or the build settings invalidates precompiled headers.
  • They're not modular. A PCH must be the first thing included from a source file (or even via the command line). As a corollary, you cannot include more than one PCH. In other words, if you distribute your library as a PCH, you're basically saying that your library is the only thing the user will ever need.

The problem is that PCHs are typically (in MSVC and GCC, Clang is slightly different) implemented as a simple dump of the internal compiler state. Loading a PCH means replacing the compiler state with the state in the PCH. There is no middle ground - compilers cannot merge the state from the PCH into their current state.

Clang's PCHs are implemented differently, but still have to be the first thing, because if anything came before the PCH, the C++ compilation model would still mean that the PCH is potentially invalid. Clang's module support basically describes a changed compilation model that allows merging PCHs. (There's also a lot of work involved in doing the merging correctly.)

Upvotes: 5

Adam Sosnowski
Adam Sosnowski

Reputation: 1284

No. Precompiled headers have can only be used by compiler that created them. For GCC it even meands the same binary.

Upvotes: 3

Related Questions