CMake 3.16: Support for Precompiled Headers and Unity Builds

cmake
Modules are coming in C++20 but it will take a while before they are widely adopted, optimized and supported by tooling.
Release of CMake 3.16 does not require resorting to 3rd party CMake scripts from GitHub for precompiled headers and unity builds:
-
To precompile means that the compiler will parse the C++ headers and save its intermediate representation (IR) into a file, and then when compiling the .cpp files of the target that IR will be prepended to them – as if the headers were included – the contents of the PCH are the first thing each translation unit sees
- Easy to integrate – doesn’t require any C++ code changes
- ~20-30% speedup with GCC/Clang (can be up to 50%+ with MSVC)
- For targets with at least 10 .cpp files (takes space & time to compile)
What to put in a PCH
- STL & third-party libs like boost (used in at least ~30% of the sources)
- Some rarely changing project-specific headers (at least 30% use)
- for example if you have common utilities for logging/etc.
- Each time any header which ends up in the PCH is changed – the entire PCH is recompiled along with the entire target which includes it
- Careful not to put too much into a PCH – once it reaches ~150-200MB you might start hitting diminishing returns
- How to determine which are the most commonly used header files
- option 1: do a few searches in the codebase/target
- <algorithm>, <vector>, <boost/asio.hpp>, etc.
- note that some header might be included only in a few other header files, but if those headers go everywhere, then the other header gets included almost everywhere as well
- option 2: – use software to visualize includes & dependencies
- option 1: do a few searches in the codebase/target
Read More »CMake 3.16: Support for Precompiled Headers and Unity Builds