...

/

Building and Managing Dependencies

Building and Managing Dependencies

Let's learn about how to build and manage dependencies in a CMake project.

All build processes work the same way. We start from the top-level listfile and navigate downward into the project source tree. The figure below shows which project files partake in the building. Numbers in parentheses indicate the order of the CMake script execution:

Press + to interact
Files used in the build stage
Files used in the build stage

Our top-level listfile will configure the project and load nested elements:

Press + to interact
cmake_minimum_required(VERSION 3.25.1)
project(Calc VERSION 1.0.0 LANGUAGES CXX)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
include(NoInSourceBuilds)
add_subdirectory(src bin)
add_subdirectory(test)
include(Install)

We start by providing key project details and adding a path to the CMake utility modules (the cmake directory in our project). We then disable in-source builds (through a custom module) and include two key directories:

  • src, containing the project source (to be named bin in the build tree)

  • test, containing all the testing utilities

Finally, we include another module that will set up the installation of the project. Meanwhile, let's take a look at the NoInSourceBuilds module to understand how it works:

Press + to interact
if(PROJECT_SOURCE_DIR STREQUAL PROJECT_BINARY_DIR)
message(FATAL_ERROR
"\n"
"In-source builds are not allowed.\n"
"Instead, provide a path to build tree like so:\n"
"cmake -B <destination>\n"
"\n"
"To remove files you accidentally created execute:\n"
"rm -rf CMakeFiles CMakeCache.txt\n"
)
endif()

No surprises here—we simply check whether the user provided a destination directory as an argument to the cmake command to store generated files. It has to be a different path than the project source tree. If that's not the case, we inform the user how to provide it and clean the repository after the mistake.

Our top-level listfile then includes the src subdirectory, instructing CMake to read the listfile in it:

add_subdirectory(calc)
add_subdirectory(calc_console)
Adding the subdirectories (File: src/CMakeLists.txt)

This file is very subtle—it simply steps into the nested directories, executing the listfiles in them. Let's follow the listfile of the calc library—it's a bit involved, so we'll discuss it in parts. ...