CMake From Scratch: A Beginner’s Guide to Building C and C++ Projects
Learn CMake by building a real C++ project, adding a library, tests, build options, presets, and installation rules, with examples for C too.
Published 20 min readCategory: Tooling
On this page
If you have written a C or C++ program, you have probably compiled it with a command like this:
c++ main.cpp -o hello./helloThat works. It is also about the point where the build process feels easy.
Now imagine that your program has 25 source files, three libraries, a test suite, and a dependency that is installed in different places on Windows, Linux, and macOS. You could keep adding file names and compiler flags to one enormous command. You could also write a different build script for every operating system.
Or you could describe what your project needs to build and let a build system handle the details.
That is where CMake (external link) comes in.
This tutorial starts with a single executable and gradually builds a small but realistic C++ project. Along the way, we will cover libraries, header directories, dependencies, tests, build configurations, presets, installation, and how the same ideas apply to C.
You do not need any previous CMake experience. Basic familiarity with C or C++ and running commands in a terminal is enough.
Table of contents
- What CMake actually does
- Installing the tools
- Your first CMake project
- Understanding CMakeLists.txt
- The configure and build workflow
- Growing into a real project
- Understanding targets and visibility
- Debug and Release builds
- Options and compile definitions
- Testing with CTest
- Making builds repeatable with presets
- Installing your program
- Working with external libraries
- Using CMake for C projects
- Useful commands and common mistakes
- Where to go next
What CMake actually does
CMake is not a compiler. It is a tool that generates a build system for your compiler and platform.
For example, CMake can generate:
- Ninja build files for the Ninja build tool.
- Unix Makefiles for
make. - Visual Studio solutions and projects on Windows.
- Xcode projects on macOS.
You generally describe your project in files named CMakeLists.txt. CMake reads those files, checks your environment, and generates instructions for the selected build tool. That build tool then invokes the C or C++ compiler and linker.
Diagram source
flowchart LR
accTitle: CMake configuration and build flow
accDescr: Source files and CMakeLists files are configured by CMake, which generates Ninja or Makefiles or IDE project files. The build tool invokes the compiler and linker to produce an executable or library.
A[Source files and CMakeLists.txt] --> B[CMake configure]
B --> C[Generated build files]
C --> D[Build tool]
D --> E[Compiler and linker]
E --> F[Executable or library]Three words are worth learning immediately:
| Word | What it means |
|---|---|
| Configure | Read the CMake project, detect tools and dependencies, and prepare the build. |
| Generate | Write the actual build files for Ninja, Make, Visual Studio, or another generator. |
| Build | Compile source files and link the executable or library. |
CMake usually performs configure and generate together when you run cmake -S ... -B ....
The big idea is that your CMake files describe the relationships between parts of the project. They should not need to list every low-level command the compiler will execute.
Installing the tools
To follow along, you need:
- CMake 3.21 or newer (this tutorial uses CMake presets version 3 later).
- A C++ compiler such as GCC, Clang, or MSVC.
- A build tool, such as Make, Ninja, or the toolchain provided by Visual Studio.
Ninja (external link) is optional for most of this tutorial, but required for the preset example because that preset explicitly selects it.
After installing your tools, check them:
cmake --versionc++ --version # Typical on Linux and macOS; not an MSVC commandninja --version # Only if you installed NinjaOn Windows, the simplest starting point is Visual Studio with its Desktop development with C++ workload, or a correctly configured Clang/GCC toolchain. If using MSVC, run CMake from a Visual Studio Developer Command Prompt or another environment where the compiler is available.
CMake does not install a compiler for you. If configuration fails because no C++ compiler was found, check the compiler installation first.
Your first CMake project
Let’s build a tiny C++ program. Make a directory named hello-cmake and add two files:
hello-cmake/├── CMakeLists.txt└── main.cppOur program will be familiar:
#include <iostream>
int main() { std::cout << "Hello from CMake!\n"; return 0;}Now create the build description:
cmake_minimum_required(VERSION 3.21)
project(HelloCMake LANGUAGES CXX)
add_executable(hello main.cpp)That is a complete CMake project: three commands.
From inside hello-cmake/, run:
cmake -S . -B buildcmake --build buildYou can then run the compiled program. With Ninja or Make on Linux/macOS, for example:
./build/helloExpected output:
Hello from CMake!On Windows, the executable is named hello.exe. Its location can depend on the generator, for example, a Visual Studio build may put it under build/Debug/.
You have just configured and built your first CMake project.
Understanding CMakeLists.txt
Let’s unpack those three lines before adding anything else.
Minimum CMake version
cmake_minimum_required(VERSION 3.21)This says your project requires at least CMake 3.21. It also establishes the CMake policy behavior associated with that version, helping the project behave predictably across newer CMake releases.
It does not mean users must install exactly version 3.21. Later compatible releases work too.
Project name and languages
project(HelloCMake LANGUAGES CXX)This declares a project named HelloCMake and says it contains C++ code.
CMake uses C for C and CXX for C++. For projects that contain both languages:
project(MyProject LANGUAGES C CXX)You can also specify a version:
project(MyProject VERSION 1.2.0 LANGUAGES C CXX)CMake then provides variables such as PROJECT_NAME and PROJECT_VERSION for use elsewhere.
Executable targets
add_executable(hello main.cpp)This creates a target named hello from main.cpp.
A target is a named thing CMake knows how to build or manage: most commonly an executable or a library. Targets can have source files, include directories, compiler requirements, definitions, and dependencies attached to them.
You can name the target almost anything sensible:
add_executable(my_cool_app main.cpp)You will spend a lot of time working with targets. They are the foundation of modern CMake.
What about variables and comments?
CMake has its own small scripting language:
# This is a comment.set(MY_MESSAGE "Hello")message(STATUS "${MY_MESSAGE}")set()assigns a variable.${MY_MESSAGE}expands that variable.message(STATUS ...)prints a message during configuration.- CMake command names are case-insensitive, but lowercase is the usual style.
One important distinction: CMake variables and cache variables are not the same thing. Cache variables persist in a build directory across configurations and are frequently set using -D, which we will see later.
The configure and build workflow
You will probably type these commands hundreds of times:
cmake -S . -B buildcmake --build buildHere is what the arguments mean:
| Argument | Meaning |
|---|---|
-S . | The source directory, where the top-level CMakeLists.txt lives. Here, . means the current directory. |
-B build | The build directory, where generated files and compiled outputs belong. |
--build build | Ask CMake to invoke the appropriate build tool for that build directory. |
The generated build/ directory might contain CMakeCache.txt, files for Ninja or Make, compiler metadata, object files, and your program.
Do not commit it to Git. Add this to .gitignore:
/build/This pattern is called an out-of-source build: project files stay in the source tree, and generated files live somewhere else.
Why not call
g++directly? Withcmake --build, the selected build tool knows which source files changed. After the initial build, it generally recompiles only what is necessary.
When you add a new source file or change CMakeLists.txt, run the configure command again. CMake-generated build systems also often detect and re-run configuration automatically when needed, but explicitly reconfiguring is a useful beginner habit.
Growing into a real project
One source file is simple. Real projects usually contain several executables, libraries, and tests. Let’s build a small calculator as an example.
By the end, the directory will look like this:
calculator/├── CMakeLists.txt├── CMakePresets.json├── .gitignore├── app/│ ├── CMakeLists.txt│ └── main.cpp├── include/│ └── calculator/│ └── operations.hpp├── src/│ ├── CMakeLists.txt│ └── operations.cpp└── tests/ ├── CMakeLists.txt └── operations_test.cppWe will have three targets:
| Target | Type | Purpose |
|---|---|---|
calculator_core | Static library | Reusable calculator functions. |
calculator_app | Executable | A program that uses the library. |
calculator_tests | Executable | Checks that the library works. |
Step 1: The top-level project
Create a new calculator/ directory with this root file:
cmake_minimum_required(VERSION 3.21)project(Calculator VERSION 1.0.0 LANGUAGES CXX)
include(GNUInstallDirs)include(CTest)
option(CALCULATOR_VERBOSE "Print extra information from the app" OFF)
add_subdirectory(src)add_subdirectory(app)
if(BUILD_TESTING) add_subdirectory(tests)endif()
install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})The important new command is add_subdirectory().
It tells CMake to process another CMakeLists.txt inside that directory. We can now keep the configuration for each part of the project near its source files.
The other lines prepare features we will cover shortly:
include(GNUInstallDirs)provides standard install directory names such asbin,lib, andinclude.include(CTest)prepares test support and aBUILD_TESTINGoption.option()creates a user-configurable setting.install()describes where headers go when the project is installed.
Do not worry about memorizing all of these immediately. We will use each one.
Step 2: Create a library
Let’s put the calculator functions in their own library so that both the application and tests can reuse them.
First, write a public header:
#pragma once
namespace calculator {int add(int left, int right);int subtract(int left, int right);}Then add the implementation:
#include "calculator/operations.hpp"
namespace calculator {int add(int left, int right) { return left + right;}
int subtract(int left, int right) { return left - right;}}Now tell CMake how to build it:
add_library(calculator_core STATIC operations.cpp)
target_compile_features(calculator_core PUBLIC cxx_std_17)set_target_properties(calculator_core PROPERTIES CXX_EXTENSIONS OFF)
target_include_directories(calculator_core PUBLIC $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
install(TARGETS calculator_core ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})This introduces several important ideas.
add_library() creates a library target. The STATIC keyword produces a static library, typically a .a file on Linux/macOS or a .lib file on Windows.
add_library(calculator_core STATIC operations.cpp)Other forms include:
add_library(shared_example SHARED shared.cpp)add_library(header_only INTERFACE)A shared library is loaded dynamically (commonly .so, .dylib, or .dll, depending on the platform). An interface library can carry requirements such as header directories without compiling its own source files.
target_compile_features() specifies the required C++ language level.
target_compile_features(calculator_core PUBLIC cxx_std_17)This tells CMake that the library and projects that link against it need at least C++17. We also turn off compiler-specific language extensions for this library with CXX_EXTENSIONS OFF.
target_include_directories() says where headers can be found.
target_include_directories(calculator_core PUBLIC $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)Because we wrote:
#include "calculator/operations.hpp"…the compiler needs calculator/include on its include-search path, not calculator/include/calculator.
The $<...> expressions are called generator expressions. These two distinguish between using the library directly from the source tree and using it after installation. For a project that will never be installed, the simpler beginner form also works:
target_include_directories(calculator_core PUBLIC ${PROJECT_SOURCE_DIR}/include)We use the install-aware version in our complete project so that the installation example will make sense later.
Step 3: Create an executable that uses the library
In the app/ directory, add:
#include <iostream>#include "calculator/operations.hpp"
int main() { std::cout << "7 + 5 = " << calculator::add(7, 5) << '\n'; std::cout << "7 - 5 = " << calculator::subtract(7, 5) << '\n';
#ifdef CALCULATOR_VERBOSE std::cout << "Verbose output is enabled.\n";#endif}And its CMake file:
add_executable(calculator_app main.cpp)
target_link_libraries(calculator_app PRIVATE calculator_core)
if(CALCULATOR_VERBOSE) target_compile_definitions(calculator_app PRIVATE CALCULATOR_VERBOSE=1)endif()
install(TARGETS calculator_app RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})Notice this line:
target_link_libraries(calculator_app PRIVATE calculator_core)This is how we express a dependency between targets. The app needs the calculator library, so we link the app to the library. CMake now knows the correct build order and link requirements.
It also learns the library’s public usage requirements, including its header directory. We do not need to repeat the include directory for calculator_app.
This is one of the most valuable reasons to use modern target-based CMake.
Understanding targets and visibility
You probably noticed the words PRIVATE and PUBLIC in the examples. CMake also has INTERFACE.
These keywords describe who receives a requirement.
| Keyword | Applied to this target? | Passed to targets that link it? |
|---|---|---|
PRIVATE | Yes | No |
PUBLIC | Yes | Yes |
INTERFACE | No | Yes |
For example:
# Only calculator_core needs this private implementation detail.target_compile_definitions(calculator_core PRIVATE INTERNAL_DIAGNOSTICS=1)
# Both calculator_core and its consumers need this directory.target_include_directories(calculator_core PUBLIC ${PROJECT_SOURCE_DIR}/include)
# Consumers of this header-only target receive its include path.add_library(project_headers INTERFACE)target_include_directories(project_headers INTERFACE ${PROJECT_SOURCE_DIR}/include)Use PRIVATE for implementation details, PUBLIC when a requirement is necessary both for the library and its consumers, and INTERFACE when only consumers need it.
Diagram source
flowchart TD
accTitle: Calculator target dependency graph
accDescr: Both the calculator app and calculator tests link privately to calculator core. The core library provides its public include directory and C++17 requirement to its consumers.
A[calculator_app] --> C[calculator_core]
B[calculator_tests] --> C
C --> D[Public headers and C++17 requirement]A useful rule: attach requirements to the target that owns them. Avoid configuring compiler flags, include paths, and definitions globally unless you actually intend them to affect every target.
For example, prefer:
target_include_directories(calculator_core PUBLIC include_path)…over the older, directory-wide style:
include_directories(include_path)The same principle applies to target_compile_definitions(), target_compile_options(), and target_link_libraries().
Debug and Release builds
You will often want two different kinds of build:
- Debug: Designed for debugging, generally with debug symbols and little or no optimization.
- Release: Generally optimized for performance, typically with debug assertions disabled when
NDEBUGis defined.
For single-configuration generators such as Ninja and Unix Makefiles, select a build type when configuring:
cmake -S . -B build/debug -DCMAKE_BUILD_TYPE=Debugcmake --build build/debugcmake -S . -B build/release -DCMAKE_BUILD_TYPE=Releasecmake --build build/releaseFor multi-configuration generators such as Visual Studio, build type is chosen at build time instead:
cmake -S . -B buildcmake --build build --config Debugcmake --build build --config ReleaseThe --config argument does not replace CMAKE_BUILD_TYPE for ordinary single-configuration Ninja/Make builds.
Keeping separate directories for Debug and Release is an easy way to avoid mixing incompatible generated files and compiler settings.
Options and compile definitions
Sometimes you want users to choose how a project is built. The option() command creates a Boolean cache option:
option(CALCULATOR_VERBOSE "Print extra information from the app" OFF)The final OFF is the default. Users can turn it on during configuration:
cmake -S . -B build -DCALCULATOR_VERBOSE=ONcmake --build buildThe -D flag sets a CMake cache entry. It does not automatically create a C++ preprocessor macro.
That is why the app has this separate CMake logic:
if(CALCULATOR_VERBOSE) target_compile_definitions(calculator_app PRIVATE CALCULATOR_VERBOSE=1)endif()target_compile_definitions() adds a definition for the compiler. In the C++ file, #ifdef CALCULATOR_VERBOSE now becomes active.
Re-run the executable and you will see:
7 + 5 = 127 - 5 = 2Verbose output is enabled.To switch it off again:
cmake -S . -B build -DCALCULATOR_VERBOSE=OFFcmake --build buildTwo different worlds:
if(CALCULATOR_VERBOSE)is evaluated by CMake while configuring.#ifdef CALCULATOR_VERBOSEis evaluated by the C++ preprocessor while compiling.
A quick note on compiler warnings
You can add warning flags to a particular target. Because different compilers accept different flags, check the toolchain:
if(MSVC) target_compile_options(calculator_core PRIVATE /W4)else() target_compile_options(calculator_core PRIVATE -Wall -Wextra -Wpedantic )endif()This is optional, but helpful. Notice that warning settings are PRIVATE: consumers of the library should decide their own warning policy.
Testing with CTest
CMake includes an accompanying testing tool called CTest. It runs test programs and reports which ones passed or failed.
Our root CMakeLists.txt already has:
include(CTest)This sets up testing and provides the BUILD_TESTING option, which defaults to ON.
Let’s write a small test program. We will return a nonzero exit code when a check fails, so the test works in both Debug and Release builds. (Plain C/C++ assert() may be compiled out when NDEBUG is enabled.)
#include <iostream>#include "calculator/operations.hpp"
int main() { if (calculator::add(2, 3) != 5) { std::cerr << "add() failed\n"; return 1; } if (calculator::subtract(2, 3) != -1) { std::cerr << "subtract() failed\n"; return 1; } return 0;}Create a target for the test executable and register it with CTest:
add_executable(calculator_tests operations_test.cpp)
target_link_libraries(calculator_tests PRIVATE calculator_core)
add_test(NAME operations COMMAND calculator_tests)Now configure, build, and run the test suite:
cmake -S . -B buildcmake --build buildctest --test-dir build --output-on-failureYou should see output similar to:
Start 1: operations1/1 Test #1: operations ....................... Passed
100% tests passed, 0 tests failed out of 1add_test() does not compile the test by itself. The add_executable() call does that; add_test() tells CTest how to run it.
To avoid building tests, configure with:
cmake -S . -B build-no-tests -DBUILD_TESTING=OFFcmake --build build-no-testsFor a multi-configuration generator, supply the relevant configuration when running tests:
ctest --test-dir build -C Debug --output-on-failureAs projects grow, you can replace this simple test executable with a framework such as GoogleTest or Catch2 while keeping CTest as the runner.
Making builds repeatable with presets
Typing long configure commands is tedious, especially if each developer needs the same options.
CMake presets put those settings into a JSON file named CMakePresets.json. Commit this file alongside your project so everyone can use the same named configurations.
Our example uses Ninja, so install Ninja before trying these presets.
{ "version": 3, "configurePresets": [ { "name": "debug", "displayName": "Debug (Ninja)", "generator": "Ninja", "binaryDir": "${sourceDir}/build/debug", "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug", "CMAKE_EXPORT_COMPILE_COMMANDS": "ON" } }, { "name": "release", "displayName": "Release (Ninja)", "generator": "Ninja", "binaryDir": "${sourceDir}/build/release", "cacheVariables": { "CMAKE_BUILD_TYPE": "Release", "BUILD_TESTING": "OFF" } } ], "buildPresets": [ { "name": "debug", "configurePreset": "debug" }, { "name": "release", "configurePreset": "release" } ], "testPresets": [ { "name": "debug", "configurePreset": "debug", "output": { "outputOnFailure": true } } ]}Now a complete Debug workflow becomes:
cmake --preset debugcmake --build --preset debugctest --preset debugFor Release:
cmake --preset releasecmake --build --preset releaseNotice that the release preset disables BUILD_TESTING, so the release directory does not have our test executable or CTest test registration.
CMAKE_EXPORT_COMPILE_COMMANDS=ON generates a compile_commands.json compilation database for generators such as Ninja and Makefiles. Tools like clangd can use it to understand each file’s include paths and compiler flags.
There are two related files worth knowing:
| File | When to use it |
|---|---|
CMakePresets.json | Shared, project-wide configurations that belong in Git. |
CMakeUserPresets.json | Personal, machine-specific configurations; normally do not commit it. |
Presets are especially useful when a team works across different machines or builds the same project in CI.
Installing your program
Building creates files in a build directory. Installing copies selected artifacts into a more useful directory structure.
Our example already contains three installation rules:
install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})install(TARGETS calculator_core ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})install(TARGETS calculator_app RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})First build, then install. For example, after building with the release preset:
cmake --install build/release --prefix ./local-installOn a typical Linux machine, this produces:
local-install/├── bin/│ └── calculator_app├── include/│ └── calculator/│ └── operations.hpp└── lib/ └── libcalculator_core.aDirectory names and binary extensions vary by platform and configuration. The --prefix flag sets a destination without needing administrator privileges.
Installing a library is not the same as making it discoverable with find_package(). A reusable CMake package also needs exported targets and package configuration files. That is a worthwhile next topic, but it is outside this first project.
Working with external libraries
Sooner or later, your project will use code that somebody else wrote. CMake provides several approaches, depending on how that dependency is distributed.
Finding a library that is already installed
Many libraries provide a CMake package. A common pattern is:
find_package(SomePackage CONFIG REQUIRED)
target_link_libraries(calculator_app PRIVATE SomePackage::SomeTarget)SomePackage and SomePackage::SomeTarget are placeholders. Use the actual names from that library’s documentation, and make sure it is installed first.
When a package provides an imported target, that target can carry the correct library locations, include directories, and other requirements. Prefer imported targets over hard-coded library file paths whenever possible.
For an example using a package supplied by CMake itself, consider a program that needs native threading support:
find_package(Threads REQUIRED)
target_link_libraries(calculator_app PRIVATE Threads::Threads)The Threads::Threads target handles toolchain-specific thread requirements where needed. Our calculator does not actually use threads; this just demonstrates the syntax.
Dependencies that are part of your source tree
If you own both projects, or a dependency has been checked out inside your repository and supports CMake, you may be able to use:
add_subdirectory(external/some_library)target_link_libraries(calculator_app PRIVATE some_library_target)This assumes that directory exists and defines some_library_target. Do not paste it into the calculator unchanged.
For dependencies fetched during configuration, CMake also provides FetchContent. Package managers such as vcpkg and Conan offer other useful workflows. Which one you choose depends on how the dependency is distributed, versioned, and deployed.
Using CMake for C projects
Everything so far has used C++, but the main ideas are the same for C.
For a pure C program, create:
hello-c/├── CMakeLists.txt└── main.c#include <stdio.h>
int main(void) { puts("Hello from C!"); return 0;}cmake_minimum_required(VERSION 3.21)project(HelloC LANGUAGES C)
add_executable(hello_c main.c)target_compile_features(hello_c PRIVATE c_std_11)set_target_properties(hello_c PROPERTIES C_EXTENSIONS OFF)Build it in exactly the same way:
cmake -S . -B buildcmake --build buildOn Linux/macOS with Ninja or Make:
./build/hello_cTo combine C and C++ source code in one project, enable both languages:
project(MixedProject LANGUAGES C CXX)
add_library(c_math STATIC c_math.c)add_executable(cpp_app main.cpp)target_link_libraries(cpp_app PRIVATE c_math)One C/C++ detail is easy to miss: when C++ code includes a header for functions implemented in C, use an extern "C" guard to avoid C++ name mangling:
#ifndef C_MATH_H#define C_MATH_H
#ifdef __cplusplusextern "C" {#endif
int add_numbers(int a, int b);
#ifdef __cplusplus}#endif
#endifThis is a C/C++ language interoperability issue, not a CMake-specific requirement.
Useful commands and common mistakes
Command cheat sheet
These are the commands you will use most frequently:
| Command | What it does |
|---|---|
cmake --version | Print the installed CMake version. |
cmake -S . -B build | Configure and generate a build directory. |
cmake -S . -B build -G Ninja | Configure explicitly using the Ninja generator. |
cmake --build build | Build the project. |
cmake --build build --parallel 4 | Build with up to four parallel jobs. |
cmake --build build --target calculator_app | Build a specific target. |
cmake -S . -B build -DNAME=VALUE | Set a CMake cache variable. |
cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug | Configure a Debug build for a single-config generator. |
cmake --build build --config Debug | Build Debug with a multi-config generator. |
ctest --test-dir build --output-on-failure | Run tests and show failure details. |
cmake --install build --prefix ./local-install | Install to a local directory. |
cmake --preset debug | Configure using a named preset. |
cmake --build --preset debug | Build using a named preset. |
ctest --preset debug | Run tests using a named preset. |
Common mistakes
| Problem | Why it happens | What to try |
|---|---|---|
cmake: command not found | CMake is not installed or is not on PATH. | Install CMake and verify cmake --version. |
No CMAKE_CXX_COMPILER could be found | A C++ compiler is missing or the environment is not configured. | Install GCC/Clang/MSVC; for MSVC, use a Developer Command Prompt. |
Could not find ... package | A dependency is not installed or CMake cannot locate its package config. | Install the dependency and follow its documented package setup; sometimes set CMAKE_PREFIX_PATH. |
| A header cannot be found | Its include directory was not provided by a target dependency. | Check target_include_directories() and target_link_libraries(). |
Target ... not found | A target was referenced before it was created, or the name is misspelled. | Check target names and add_subdirectory() order. |
| Build configuration seems stuck | Old settings remain in the build cache. | Reconfigure with -D..., or start a fresh build directory. |
| CMake complains about the generator | The directory was previously configured with a different generator. | Use a new build directory rather than switching generators in place. |
| Works on Linux, not Windows | Platform-specific flags, paths, or assumptions slipped in. | Prefer target APIs and imported dependency targets; inspect compiler-specific settings. |
Choosing a compiler
CMake normally detects a suitable compiler during the first configuration. You can request one explicitly when starting with a new build directory:
cmake -S . -B build-clang -DCMAKE_CXX_COMPILER=clang++cmake --build build-clangFor C, use CMAKE_C_COMPILER. You can also use the CC and CXX environment variables before the first configure. Changing compilers in an already-configured directory is not a reliable way to switch toolchains; create another build directory instead.
Three habits that make CMake easier
- Think in targets, not files. Ask which executable or library owns a source file, include path, or compiler option.
- Keep generated output separate. Use an out-of-source build and ignore its directory in Git.
- Prefer relationships over manual paths. Link a target to the library it needs and let that library publish its usage requirements.
Where to go next
You now know enough CMake to structure many small and medium-sized C and C++ projects. You can create executables and libraries, connect them, choose language standards, set options, run tests, and install artifacts.
The next concepts worth exploring are exported CMake packages, toolchain files and cross-compilation, dependency management with FetchContent or package managers, and continuous integration with presets.
The official documentation is the best reference when a command has more arguments than you remember:
- Official CMake tutorial (external link)
- CMake command reference (external link)
- CMake build system concepts (external link)
- CMake presets reference (external link)
- CTest reference (external link)
CMake can look like a strange language at first. The turning point comes when you stop treating CMakeLists.txt as a list of compiler commands and start treating it as a description of your project’s parts and how they fit together.
Related articles
Devlog: Building Gildenkrieg’s Networking Foundation
A look at the decisions, tradeoffs, and lessons behind building a serious networking layer for Gildenkrieg.
Published Updated 9 min readCategory: Game Development
Gildenkrieg Simulation Devlog, Part 1: Entities That Survive the Network
How Gildenkrieg uses EnTT, stable network identities, versioned entity recipes, and deferred lifecycle commands to build a multiplayer-ready entity API.
Published Updated 8 min readCategory: Game Development
Gildenkrieg Simulation Devlog, Part 2: Fixed Ticks, Physics, and Replication
How Gildenkrieg advances one authoritative simulation, bridges ECS state to physics, replicates component fragments per connection, and interpolates remote players.
Published Updated 10 min readCategory: Game Development