Managing the Process of Compilation
Let's learn how processes can be used to reduce compilation time.
As programmers and build engineers, we need to consider the other aspects of compilation as well—the time it takes to complete and how easy it is to spot and fix mistakes made during the process of building a solution.
Reducing compilation time
In busy projects that require many dozens of recompilations per day (or per hour), it's paramount that compilation is as quick as possible. This not only affects how tight our code-compile-test loop is but also affects our concentration and flow of work. Luckily, C++ is already pretty good at managing compilation time, thanks to separate translation units. CMake will take care of only recompiling sources that were impacted by recent changes. However, if we need to improve things even more, there are a couple of techniques we can use: header precompilation and unity builds.
Precompilation of headers
Header files (.h
) are included in the translation unit by the preprocessor before the actual compilation begins. It means that they have to be recompiled every time the .cpp
implementation files change. On top of that, if multiple translation files are using the same shared header, it has to be compiled every time it's included. This is wasteful, but that's how things were for a long time.
Luckily, since version 3.16, CMake offers a command to enable header precompilation. This allows a compiler to process headers separately from the implementation file and speed up the compilation. This is the syntax for the provided command:
Get hands-on with 1400+ tech skills courses.