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.gchand uses it automatically whenheader.his included and a.gchsits next to it. - Clang writes
.pchfiles and loads them with-include-pch. - MSVC uses
/Yc(create) and/Yu(use) with astdafx.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
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":
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 '^