Skip to content

Lesson 7 of 9 · 25m

CMake Without the Fog: Targets, Presets, and Reproducible Builds

Build modern CMake projects around target-scoped properties, dependency boundaries, presets, and CI-reproducible configure commands.

Most C++ build pain is self-inflicted: global flags, directory-wide include paths, generated files nobody can reproduce, and a CI command that only one senior engineer remembers. Modern CMake is effective when targets are the unit of dependency and build configuration is code. If add_compile_options appears before the first target, the file is already drifting toward trouble.

Targets are the API

A minimal healthy project looks like this:

cmake_minimum_required(VERSION 3.24)
project(netd VERSION 1.4.0 LANGUAGES CXX)
add_library(netd_core src/config.cpp src/session.cpp)
add_library(netd::core ALIAS netd_core)
target_compile_features(netd_core PUBLIC cxx_std_20)
target_include_directories(netd_core PUBLIC include PRIVATE src)
target_link_libraries(netd_core PUBLIC Threads::Threads)
add_executable(netd src/main.cpp)
target_link_libraries(netd PRIVATE netd::core)

PUBLIC means consumers need it. PRIVATE means implementation detail. INTERFACE means usage requirement only. If you cannot explain why a dependency is public, make it private.

Dependencies without folklore

Prefer packages supplied by the dependency; pin source dependencies exactly because a floating branch is not a reproducible build input:

find_package(OpenSSL REQUIRED)
target_link_libraries(netd_core PRIVATE OpenSSL::SSL OpenSSL::Crypto)
include(FetchContent)
FetchContent_Declare(expected GIT_REPOSITORY https://github.com/TartanLlama/expected.git GIT_TAG v1.1.0)
FetchContent_MakeAvailable(expected)

Presets remove shell folklore

CMakePresets.json captures configure intent in the repository. Compact JSON is fine; the meaning is what matters:

{"version":3,"configurePresets":[{
"name":"linux-asan","generator":"Ninja",
"binaryDir":"${sourceDir}/build/linux-asan",
"cacheVariables":{"CMAKE_BUILD_TYPE":"RelWithDebInfo","CMAKE_EXPORT_COMPILE_COMMANDS":"ON"}
}]}

Now CI and developers run the same commands:

cmake --preset linux-asan
cmake --build --preset linux-asan
ctest --test-dir build/linux-asan --output-on-failure

CMAKE_EXPORT_COMPILE_COMMANDS feeds clang-tidy and editors. Define test and sanitizer switches as explicit option(...) cache variables, and keep warning flags in one interface target instead of mutating global state in random subdirectories.

Field notes

  • file(GLOB sources CONFIGURE_DEPENDS src/*.cpp) hides translation-unit changes from review; explicit source lists age better.
  • CMAKE_CXX_STANDARD globally is weaker than target-scoped target_compile_features usage requirements.
  • If CI and local builds differ, compare compiler version, generator, build type, dependency resolution, and cache variables before blaming the compiler.

Was this lesson helpful?

Sign in to rate