This project demonstrates the impact of Precompiled Headers (PCH) on C++ compile times using CMake.
It builds the same set of source files twice:
- Without PCH →
test_no_pch - With PCH →
test_with_pch
By comparing build times, you can see how much precompiled headers reduce compilation time in larger C++ projects.
.
├── CMakeLists.txt
├── pch.hpp
├── heavy.hpp
├── file1.cpp
├── file2.cpp
├── ...
├── include/
└── README.md
-
pch.hpp Contains headers that are expensive to compile and are shared across many source files.
-
heavy.hpp Simulates a heavy header with many includes.
-
file.cpp* Multiple source files that include the heavy headers.
-
CMake 3.20+
-
A C++ compiler supporting C++20
- GCC
- Clang
- MSVC
Create a build directory and configure the project:
mkdir build
cd build
cmake ..Build the executables:
cmake --build .This will generate two binaries:
test_no_pch
test_with_pch
To measure compilation performance, you can use the time command.
time cmake --build build --target test_no_pchtime cmake --build build --target test_with_pchYou should observe faster compile times with PCH, especially when many source files include the same heavy headers.
Large C++ projects often include the same headers across hundreds of files.
Examples:
<vector><string><iostream><algorithm>
Compilers must normally re-parse these headers for every .cpp file.
Precompiled Headers solve this by:
- Compiling commonly used headers once
- Reusing the compiled representation for all source files
This can significantly reduce build times in large projects.
CMake provides built-in support:
target_precompile_headers(test_with_pch
PRIVATE pch.hpp
)This instructs CMake to generate a precompiled header from pch.hpp and use it for the target.
To stress test compilation performance, you can generate many source files:
for i in {1..100}; do
cat <<EOF > file$i.cpp
#include "heavy.hpp"
int func$i()
{
std::vector<int> v = {1,2,3,4,5};
return v.size();
}
EOF
donePrecompiled headers can dramatically reduce compile times when:
- Many translation units include the same headers
- Headers are large or template-heavy
- The project contains hundreds of source files
However, PCH must be managed carefully to avoid unnecessary rebuilds.
This project is intended for educational and benchmarking purposes.