TExcelTAD

Precompiled Headers

If every TU starts by parsing the same 50 000 lines of standard and third-party headers, why not parse them once and save the result? That's a precompiled header (PCH): the compiler parses a header, serialises its internal state (the AST, macros, instantiated templates) to a file, and later TUs load that state instead of parsing the text again.

  • GCC writes header.gch and uses it automatically when header.h is included and a .gch sits next to it.
  • Clang writes .pch files and loads them with -include-pch.
  • MSVC uses /Yc (create) and /Yu (use) with a stdafx.h/pch.h.

You don't want to manage any of that by hand. Since 3.16, CMake does it for you with target_precompile_headers.

target_precompile_headers

cmake
target_precompile_headers(app PRIVATE
  <map> <string> <vector> <regex>          # angle brackets: system headers
  "src/common.hpp"                         # quotes: project headers, relative to the source dir
)

CMake generates cmake_pch.hxx that includes those headers, adds a build step that precompiles it, and force-includes it into every source file of the target (-include cmake_pch.hxx for GCC/Clang, /FI for MSVC). Your source files don't change. PUBLIC/INTERFACE work as for other usage requirements, so a library can hand its PCH list to the targets that link it.

Proving it with -H

This session builds the same five-file project twice, once without and once with a PCH, with -H added to the flags so the compiler reports every header it opens. A line starting with ! means "loaded this precompiled header":

bash · try it yourself
mkdir -p pch/src && cd pch
cat > src/common.hpp <<'H'
#pragma once
#include <map>
#include <regex>
#include <string>
#include <vector>
H
for n in lexer parser eval report; do cat > src/$n.cpp <<SRC
#include "common.hpp"
int $n() { std::map<std::string, std::vector<int>> m; m["$n"].push_back(1);
  return std::regex_match("$n", std::regex("[a-z]+")) + int(m.size()); }
SRC
done
echo 'int lexer(); int parser(); int eval(); int report(); int main() { return lexer() + parser() + eval() + report() - 8; }' > src/main.cpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Pch CXX)
option(USE_PCH "precompile the heavy headers" OFF)
add_executable(app src/main.cpp src/lexer.cpp src/parser.cpp src/eval.cpp src/report.cpp)
if(USE_PCH)
  target_precompile_headers(app PRIVATE <map> <regex> <string> <vector>)
endif()
CM
for mode in OFF ON; do
  cmake -S . -B build-$mode -G Ninja -DUSE_PCH=$mode -DCMAKE_CXX_FLAGS=-H > /dev/null
  cmake --build build-$mode > build-$mode.log 2>&1
  echo "USE_PCH=$mode: $(grep -c '^\[' build-$mode.log) commands," \
       "$(grep -c '^\.' build-$mode.log) header opens," \
       "$(grep -c '^!' build-$mode.log) PCH loads"
done
./build-ON/app && echo "app with PCH runs"
echo "--- the generated header:"
grep -v '^
  

 build-ON/CMakeFiles/app.dir/cmake_pch.hxx
USE_PCH=OFF: 6 commands, 1052 header opens, 0 PCH loads
USE_PCH=ON: 7 commands, 20 header opens, 5 PCH loads
app with PCH runs
--- the generated header:
/* generated by CMake */
#pragma GCC system_header
#ifdef __cplusplus
#include <map>
#include <regex>
#include <string>
#include <vector>
#endif // __cplusplus
  • Without a PCH, the four heavy TUs each open ~263 headers: over a thousand header opens in total.
  • With the PCH, the heavy headers are parsed once, by the extra command that builds cmake_pch.hxx.gch (GCC's -H stays quiet while it writes a .gch, so that one-time parse isn't in the count). Each of the five TUs then loads the .gch (!) and opens only four files of its own: 20 header opens for the whole build instead of 1052.

The work saved grows with the number of TUs: one extra command, but N − 1 fewer parses of the heavy headers. With 4 TUs it's a modest win; with 400 TUs that include the same Qt or Boost headers it's often 30–60% off a clean build.

What it costs

bash · try it yourself
mkdir -p cost/src && cd cost
printf '#include <map>\n#include <string>\nint a() { return std::map<std::string, int>{{"a", 1}}.size(); }\n' > src/a.cpp
printf '#include <map>\n#include <string>\nint b() { return std::map<std::string, int>{{"b", 1}}.size(); }\n' > src/b.cpp
printf 'int a(); int b();\nint main() { return a() + b() - 2; }\n' > src/main.cpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Cost CXX)
add_executable(app src/main.cpp src/a.cpp src/b.cpp)
target_precompile_headers(app PRIVATE <map> <string>)
CM
cmake -S . -B build -G Ninja > /dev/null && cmake --build build > /dev/null
gch=build/CMakeFiles/app.dir/cmake_pch.hxx.gch
echo "PCH file is over 10 MB: $( [ "$(stat -c %s $gch)" -gt 10000000 ] && echo yes || echo no )"
echo "objects under 2 MB: $(find build -name '*.cpp.o' -size -2048k | wc -l) of 3"
echo "--- edit a header that is in the PCH list? Simulate by changing the list:"
sed -i 's/<map> <string>/<map> <string> <vector>/' CMakeLists.txt
cmake --build build | grep -c '^\[.*Building'
PCH file is over 10 MB: yes
objects under 2 MB: 3 of 3
--- edit a header that is in the PCH list? Simulate by changing the list:
4

The trade-offs:

  • Every TU depends on the PCH. Change anything in it (the list, or a project header it includes) and every file of the target recompiles, here all three plus the PCH itself. So put only stable headers in a PCH: the standard library, third-party libraries, rarely edited core headers. Never a header you edit daily.
  • PCH files are big (tens of MB with GCC) and specific to one compiler, one set of flags and one target. That's disk and cache space, and with ccache you need extra settings (compiler_check, sloppiness).
  • Hidden dependencies. Because every file silently gets <map>, code that forgets #include <map> still compiles, and breaks when the PCH is removed or used elsewhere. Build without PCH in one CI job to catch it.
  • Distributed builds must ship the PCH to every worker, which reduces the gain.

Sharing one PCH: REUSE_FROM

Precompiling the same headers once per target wastes work when ten targets use the same list. target_precompile_headers(test_app REUSE_FROM app) makes test_app use app's PCH, as long as the targets have compatible flags (same compile options, definitions and language standard; CMake warns or fails otherwise). A common layout is a small pch object library that owns the list and that every target reuses.

Test yourself

What does target_precompile_headers(app PRIVATE <map> <string>) do to the source files of app?

  1. Rewrites their #include lines
  2. Nothing visible: CMake force-includes the generated cmake_pch.hxx when compiling them
  3. Merges them into one file
  4. Removes their includes

Why should frequently edited project headers stay out of the PCH?

  1. They can't be precompiled
  2. Any change to the PCH recompiles every TU of the target
  3. They make the PCH smaller
  4. CMake forbids it

In the -H session, what did a line starting with ! mean?

  1. A compile error
  2. The compiler loaded a precompiled header
  3. A missing header
  4. A header skipped by #pragma once