Project Partitioning

Let's learn about the project partition in CMake.

Separation of concerns

As our solutions grow in the number of lines and files they have, we slowly understand that the inevitable is coming: either we start partitioning the project or we drown in lines of code and a multitude of files. We can approach this problem in two ways: by portioning the CMake code and by moving the source files to subdirectories. In both cases, we aim to follow the design principle called separation of concerns. Put simply, break the code into chunks, grouping code with closely related functionality while decoupling other pieces of code to create strong boundaries.

Partitioning CMake code

We talked a bit about partitioning CMake code when discussing listfiles in the "First Steps with CMake" chapter. We spoke about the include() command, which allows CMake to execute the code from an external file. Calling include() doesn't introduce scopes or isolations that are not defined within the file (if the included file contains functions, their scope will be handled correctly upon calling).

This method helps with the separation of concerns, but only a little—specialized code is extracted to separate files and can even be shared across unrelated projects, but it can still pollute the global variable scope with its internal logic if the author is not careful. An old truth in programming is that even the worst mechanism is better than the best intentions.

Get hands-on with 1200+ tech skills courses.