CMake Project Structure Guide: Reusable Builds for Libraries, Tests, and Applications
CMakeC++build systemscompilerstesting

CMake Project Structure Guide: Reusable Builds for Libraries, Tests, and Applications

CCircuit Dev Hub Editorial Team
2026-11-30
6 min read

Organize CMake targets, dependencies, tests, generated files, and install rules with reusable structures and troubleshooting checklists.

A maintainable CMake project makes each library, executable, test, dependency, and generated file explicit. This guide provides a reusable project structure, modern CMake patterns, practical templates, and a troubleshooting checklist for embedded and systems software.

Overview

Modern CMake is most reliable when it describes targets rather than configuring the entire build globally. A target can be a library, executable, test helper, or generated artifact. Its source files, include directories, compiler features, link dependencies, and compile definitions should be attached to that target with commands such as target_sources(), target_include_directories(), target_compile_features(), and target_link_libraries().

A small project can begin with one CMakeLists.txt, but separating production code, tests, examples, and build support early makes future changes safer. The following structure works for a conventional C or C++ project and can be adapted for firmware libraries or host-side systems tools:

project-root/
├── CMakeLists.txt
├── cmake/
│   └── project-options.cmake
├── include/
│   └── acme/
│       └── sensor.hpp
├── src/
│   ├── sensor.cpp
│   └── CMakeLists.txt
├── app/
│   ├── main.cpp
│   └── CMakeLists.txt
├── tests/
│   ├── CMakeLists.txt
│   └── sensor_tests.cpp
├── examples/
│   └── CMakeLists.txt
├── third_party/
├── docs/
└── build/                  # generated, ignored by version control

Keep generated files out of the source tree. An out-of-source build prevents compiler output, CMake caches, generated headers, and test results from obscuring the files reviewed by developers.

Root CMakeLists.txt template

cmake_minimum_required(VERSION 3.20)

project(acme_sensor
  VERSION 0.1.0
  LANGUAGES CXX
)

include(CTest)

option(ACME_BUILD_TESTS "Build tests" ON)
option(ACME_BUILD_EXAMPLES "Build examples" OFF)

add_subdirectory(src)
add_subdirectory(app)

if(ACME_BUILD_TESTS)
  enable_testing()
  add_subdirectory(tests)
endif()

if(ACME_BUILD_EXAMPLES)
  add_subdirectory(examples)
endif()

The minimum version is a project compatibility decision, not a number to copy blindly. Select a version supported by the project’s CI, developer machines, and distribution environment, then test that baseline. If the build uses a newer command or policy, raise the requirement deliberately rather than allowing configuration to fail later.

Checklist by scenario

When adding a reusable library

Define a named target and make its public interface visible through target properties:

add_library(acme_sensor
  sensor.cpp
)

target_include_directories(acme_sensor
  PUBLIC
    ${PROJECT_SOURCE_DIR}/include
)

target_compile_features(acme_sensor PUBLIC cxx_std_20)

target_compile_warnings(acme_sensor PRIVATE)

add_library(acme::sensor ALIAS acme_sensor)

In a real project, define warning options conditionally or in a small helper module rather than assuming every compiler accepts the same flags. Use PUBLIC when consumers need the setting, PRIVATE when it applies only while compiling the target, and INTERFACE for requirements used only by consumers.

For a library with a public header, place headers under an include directory that mirrors the include name. Consumers can then write #include <acme/sensor.hpp> without depending on the repository’s internal layout.

When adding an application

add_executable(sensor_cli main.cpp)

target_link_libraries(sensor_cli
  PRIVATE
    acme::sensor
)

The application should link to the library target, not repeat its source files or manually reconstruct its include paths. This keeps the dependency graph clear and prevents subtle differences between the library used by tests and the library used by the application.

When adding tests

add_executable(sensor_tests sensor_tests.cpp)
target_link_libraries(sensor_tests PRIVATE acme::sensor)

add_test(NAME sensor_tests COMMAND sensor_tests)

If a test framework is required, discover or provide it explicitly. For a system-installed package, a typical pattern is:

find_package(Catch2 CONFIG REQUIRED)
target_link_libraries(sensor_tests PRIVATE Catch2::Catch2WithMain)

Keep test registration close to the test target. A test that compiles but is never registered with add_test() does not protect the project in continuous integration.

When adding a dependency

Prefer imported targets from find_package() when the dependency is installed and managed by the platform or a package manager:

find_package(ZLIB REQUIRED)
target_link_libraries(acme_sensor PRIVATE ZLIB::ZLIB)

For a small, reproducible dependency that is not expected to be supplied by the host, FetchContent can be appropriate:

include(FetchContent)

FetchContent_Declare(
  example_lib
  GIT_REPOSITORY https://example.invalid/example/lib.git
  GIT_TAG        v1.2.3
)
FetchContent_MakeAvailable(example_lib)

target_link_libraries(acme_sensor PRIVATE example::lib)

Pin a reviewed revision, document why the dependency is needed, and consider whether network access during configuration is acceptable for offline builds and release environments. For embedded work, a toolchain file and vendor SDK often provide the dependency targets; consume those targets instead of hard-coding host paths.

What to double-check

  • Compiler standard: Set the required language level with target_compile_features() or a target-specific standard property. Avoid relying on a compiler’s default mode.
  • Toolchain selection: Configure cross-compilation with a toolchain file that defines the compiler, target system, search behavior, and any required SDK settings. Do not mix host libraries into a firmware build accidentally.
  • Link order and visibility: Attach dependencies to the target that uses them. Review PUBLIC, PRIVATE, and INTERFACE visibility when a consumer cannot find headers or symbols.
  • Generated files: Place generated headers in the build tree and add their binary directory to the relevant target. If generation has a tool dependency, express it with add_custom_command() and target dependencies rather than relying on command order.
  • Install rules: If the library is consumed outside the source tree, define install destinations for targets and public headers. Export targets with a namespace so installed usage resembles build-tree usage.
  • Generator behavior: Single-configuration generators commonly use -DCMAKE_BUILD_TYPE=Debug or Release at configure time. Multi-configuration generators select the configuration during the build command, for example with --config Debug. Do not assume one workflow works unchanged for both.

Useful command reference

  • cmake -S . -B build configures an out-of-source build.
  • cmake --build build builds using the selected generator.
  • ctest --test-dir build --output-on-failure runs tests and prints failing test output.
  • cmake --build build --target help lists targets supported by the generator.
  • cmake --build build --target clean removes build outputs where supported.

Common mistakes

Using global include paths and compiler flags. Commands such as include_directories() and broad directory-wide flags make unrelated targets depend on hidden state. Prefer target-scoped commands.

Building in the source directory. A stale cache can preserve an old compiler, option, or dependency path. Delete the build directory and configure a fresh one when changing toolchains or diagnosing unexplained behavior.

Adding library source files directly to every executable. This can create duplicate symbols and causes each consumer to maintain its own incomplete list. Build one library target and link it.

Confusing configuration with compilation. Errors from cmake -S . -B build concern discovery, policies, toolchains, or generated build files. Errors from cmake --build build concern compilation or linking. Diagnose the stage first.

Assuming a package name equals a target name. The name passed to find_package() may not be the target used by target_link_libraries(). Check the package’s documented imported targets and avoid manually guessing library paths.

Registering tests only in one build mode. Keep test discovery and registration controlled by a clear option, and verify that the default CI configuration actually enables and runs the intended tests.

When to revisit

Revisit this CMake project structure whenever a project changes compiler, host platform, embedded toolchain, dependency source, or test framework. It is also worth reviewing before a release, after upgrading CMake, or when introducing a new generator or continuous-integration environment. CMake commands, compiler capabilities, package configurations, and SDK layouts can change independently, so validate the project’s chosen minimum version and toolchain assumptions against the environments that matter to the team.

Use this short action checklist before committing a build change:

  1. Configure from a clean build directory with the intended toolchain.
  2. Build the library, applications, and examples that are enabled for the scenario.
  3. Run ctest --test-dir build --output-on-failure.
  4. Confirm that public headers work from an external consumer or install-style test.
  5. Inspect the generated compile and link commands when a flag or dependency behaves unexpectedly.
  6. Record new options, minimum-version changes, and dependency decisions in project documentation.

A good CMake project is not defined by its number of files. It is defined by an understandable target graph, reproducible configuration, isolated build output, and tests that run through the same dependency relationships as the application.

Related Topics

#CMake#C++#build systems#compilers#testing
C

Circuit Dev Hub Editorial Team

Technical Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.