Precompiled Headers in C++
Precompiled headers are a performance optimization for C/C++ compilers that compile a stable set of header files into an intermediate form (a file with an extension like
.pchor.gchin the GNU Compiler Collection) and save the compiled state to a binary file, significantly speeding up subsequent compilations by skipping the parsing and tokenization of those headers. This is particularly useful for large projects or when a common set of headers is included in many source files. The compiled header is then included at the beginning of source files, which acts as a stand-in for the original headers and avoids recompiling them unless the precompiled files themselves are changed.
The ideas of precompiled headers were central to the development of C++ modules. Modules allow greater encapsulation and control of exported symbols, and like precompiled headers allow for faster compilation. Modules are handled entirely by the compiler rather than the preprocessor, and thus unlike precompiled headers, cannot export macros due to being handled after the preprocessing step.
GCC
Precompiled headers are supported in GCC (3.4 and newer). GCC's approach is similar to these of VC and compatible compilers. GCC saves precompiled versions of header files using a .gch suffix. When compiling a source file, the compiler checks whether this file is present in the same directory and uses it if possible.
GCC can only use the precompiled version if the same compiler switches are set as when the header was compiled and it may use at most one. Further, only preprocessor instructions may be placed before the precompiled header (because it must be directly or indirectly included through another normal header, before any compilable code).
GCC automatically identifies most header files by their extension. However, if this fails (e.g. because of non-standard header extensions), the -x switch can be used to ensure that GCC treats the file as a header.
(See also https://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html)
clang
The clang compiler added support for PCH in Clang 2.5 / LLVM 2.5 of 2009. The compiler both tokenizes the input source code and performs syntactic and semantic analyses of headers, writing out the compiler's internal generated abstract syntax tree (AST) and symbol table to a precompiled header file.
clang's precompiled header scheme, with some improvements such as the ability for one precompiled header to reference another, internally used, precompiled header, also forms the basis for its modules mechanism. It uses the same bitcode file format that is employed by LLVM, encapsulated in clang-specific sections within Common Object File Format or Extensible Linking Format files.