TExcelTAD
Home › Modern CMake (with CTest & CPack) › Field Notes: Structuring Real Projects

Field Notes: Structuring Real Projects

The anti-patterns are about what not to write. These notes are about shape: how to organise a CMake project so it stays pleasant at 5 targets and at 500, and so other projects can consume it without patches.

One target per concept

A target is the unit of everything: sources, usage requirements, tests, install rules. Make one per concept (a library with a clear job, a program, a test binary), not one per directory and not one for the whole project.

  • A "god library" (add_library(engine ${EVERYTHING})) means every change recompiles and relinks everything, and every consumer sees every dependency.
  • A target per folder of three files creates link-order noise and slow configures.
  • A good test: can you describe the target in one sentence, and would its target_link_libraries list be short and honest?

Make your project consumable

Your project will eventually be used by someone else through add_subdirectory, FetchContent or find_package. Four habits make all three work:

  1. Namespaced ALIAS targets that match the installed names: add_library(Shapes::geometry ALIAS geometry). Consumers write the same line either way.
  2. Prefixed options (SHAPES_BUILD_TESTS, not BUILD_TESTS).
  3. No global state: no CMAKE_CXX_FLAGS edits, no include_directories, no set(CMAKE_CXX_STANDARD …) that overrides the parent's choice (use target_compile_features).
  4. Top-level-only extras: tests, examples, packaging and developer warnings only when the project is the top-level build.
bash · try it yourself
# --- a library that behaves well when embedded
mkdir -p shapes/tests && cd shapes
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Shapes VERSION 1.0.0 LANGUAGES CXX)

option(SHAPES_BUILD_TESTS "Build Shapes' tests" ${PROJECT_IS_TOP_LEVEL})

add_library(geometry area.cpp)
add_library(Shapes::geometry ALIAS geometry)
target_compile_features(geometry PUBLIC cxx_std_17)

if(SHAPES_BUILD_TESTS)
  enable_testing()
  add_subdirectory(tests)
endif()
message("Shapes: top-level=${PROJECT_IS_TOP_LEVEL}, tests=${SHAPES_BUILD_TESTS}")
CM
echo 'double area(double s) { return s * s; }' > area.cpp
cat > tests/CMakeLists.txt <<'CM'
add_executable(geometry_test test.cpp)
target_link_libraries(geometry_test PRIVATE Shapes::geometry)
add_test(NAME geometry_test COMMAND geometry_test)
CM
echo 'double area(double); int main() { return area(3) == 9 ? 0 : 1; }' > tests/test.cpp

echo "=== built on its own"
cmake -S . -B build -G Ninja --log-level=NOTICE 2>&1 | grep '^Shapes'
cmake --build build > /dev/null && ctest --test-dir build | grep 'tests passed'

# --- an application that embeds it
mkdir -p ~/app && cd ~/app
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(App LANGUAGES CXX)
add_subdirectory(../shapes shapes)
add_executable(app main.cpp)
target_link_libraries(app PRIVATE Shapes::geometry)
CM
echo 'double area(double); int main() { return area(2) == 4 ? 0 : 1; }' > main.cpp
echo "=== embedded with add_subdirectory"
cmake -S . -B build -G Ninja --log-level=NOTICE 2>&1 | grep '^Shapes'
cmake --build build | grep -c test || true
=== built on its own
Shapes: top-level=ON, tests=ON
100% tests passed out of 1
=== embedded with add_subdirectory
Shapes: top-level=OFF, tests=OFF
0

Embedded, the library didn't build its tests (0 lines mentioning test in the app's build), but a parent that wants them can still pass -DSHAPES_BUILD_TESTS=ON. The default comes from PROJECT_IS_TOP_LEVEL, which is the whole trick.

Layout conventions that pay off

text
project/
├── CMakeLists.txt          # minimum version, project(), options, add_subdirectory, packaging last
├── CMakePresets.json       # dev/CI configurations
├── cmake/                  # helper modules + Config.cmake.in
├── src/<lib>/              # library sources + private headers
├── include/<project>/      # public headers, included as <project/...>
├── apps/                   # executables
├── tests/                  # test executables, add_test calls
└── examples/, docs/, tools/
  • Public headers under include/<project>/ so users write #include <shapes/area.hpp>; private headers next to the sources.
  • The top-level file reads like a table of contents: settings, then add_subdirectory() calls, then install and packaging.

Dependencies: pick one strategy per project

Mixing find_package for some libraries, FetchContent for others and vendored copies for the rest works until two of them bring different versions of the same library. Decide early:

Strategy Good for Watch out for
find_package only, dependencies provided by a package manager (Conan, vcpkg) or the system applications, teams, CI caching needs the package manager set up (presets help)
FetchContent with FIND_PACKAGE_ARGS small libraries, header-only deps, test frameworks full rebuilds of dependencies, their CMake quality
vendored copies (third_party/) patched or abandoned dependencies updates are manual; old cmake_minimum_required lines break on CMake 4

In every case, consume dependencies through find_package-style imported targets (fmt::fmt), so you can switch strategies without touching the targets. The package-manager route is the subject of C/C++ Packages: Conan 2, vcpkg & CPM.cmake.

Warnings and sanitizers as targets, not flags

Keep project-wide compile settings in INTERFACE targets and link them where they apply:

cmake
add_library(shapes_warnings INTERFACE)
target_compile_options(shapes_warnings INTERFACE
  
lt;
lt;CXX_COMPILER_ID:GNU,Clang>:-Wall -Wextra -Wpedantic>
lt;
lt;CXX_COMPILER_ID:MSVC>:/W4 /permissive->) if(PROJECT_IS_TOP_LEVEL AND SHAPES_WARNINGS_AS_ERRORS) target_compile_options(shapes_warnings INTERFACE
lt;IF:
lt;CXX_COMPILER_ID:MSVC>,/WX,-Werror>) endif() target_link_libraries(geometry PRIVATE shapes_warnings)

Don't install or export it (link it PRIVATE, or wrap it in

lt;BUILD_INTERFACE:…>), so consumers never inherit your warning policy. -Werror belongs in CI and developer presets, not in the default build: a new compiler version with a new warning shouldn't break every user's build.

Small habits

  • Keep CMakeLists.txt declarative: functions for repetition, but no clever logic deciding what a target is.
  • Run CMake's own linting in CI: -Wdev -Wdeprecated -Wuninitialized on a fresh configure.
  • Pin the CMake version in CI (the official binaries, pip install cmake==4.4.4, or a container) and bump it deliberately, as Policies & CMake 4 describes.
  • Format CMake files with gersemi or cmake-format, and review CMakeLists.txt changes like code: they are.

Test yourself

How should a library decide whether to build its tests by default?

  1. Always build them
  2. Default the option to PROJECT_IS_TOP_LEVEL, so they build only when the library is the top-level project
  3. Never build them
  4. Check CMAKE_BUILD_TYPE

Why link a warnings INTERFACE target PRIVATE (or wrap it in BUILD_INTERFACE)?

  1. It is faster
  2. So consumers of your installed or embedded library don't inherit your warning flags
  3. INTERFACE targets can't be PUBLIC
  4. To enable -Werror

What is the main risk of mixing find_package, FetchContent and vendored copies?

  1. Slower configure
  2. Two routes can bring different versions of the same library into one build
  3. CMake forbids it
  4. Packages can't be installed