CMake Hands-On Exercises
This article shows how to use CMake to manage a C++ project of medium complexity, covering the full flow from project creation to compiling and running.
It covers basic configuration, library linking, unit testing, custom commands and advanced features such as cross-platform cross compilation.
CMake Build Flow
The following diagram shows the complete CMake build flow from source code to the final executable:
Project overview
We will build a C++ project containing a main program, a static library and unit tests.
The library provides math operations (addition, subtraction, multiplication); the main program calls them and the tests verify correctness.
Project directory structure
MyProject/
├── CMakeLists.txt # 根构建配置(项目定义、全局设置)
├── src/
│ ├── main.cpp # 主程序入口
│ ├── CMakeLists.txt # src 子目录构建配置(库 + 可执行文件)
│ ├── lib/
│ │ ├── module1.cpp # 数学模块一:加法、减法
│ │ └── module2.cpp # 数学模块二:乘法
│ └── include/
│ └── mylib.h # 公共头文件(函数声明)
└── tests/
├── test_main.cpp # 单元测试用例
└── CMakeLists.txt # 测试子目录构建配置
Out-of-Source Buildis a CMake best practice: all build artifacts (Makefile, object files, executables) go into a separate build directory and never pollute the source tree.
Create the CMakeLists.txt file
CMakeLists.txt is CMake's core configuration file and uses a hierarchical structure, with one in the root directory and one in each subdirectory.
Root directory CMakeLists.txt
The root configuration defines project-level information and manages subdirectories through add_subdirectory.
Example
cmake_minimum_required
(
VERSION
3.10
)
Specify the minimum required CMake version
project
(
MyProject VERSION
1.0
)
Define the project name and version number
Set the C++ standard to C++11 and make it mandatory
set
(
CMAKE_CXX_STANDARD
11
)
set
(
CMAKE_CXX_STANDARD_REQUIRED ON
)
Add a global header search path (PROJECT_SOURCE_DIR is the project root)
include_directories
(
$
{
PROJECT_SOURCE_DIR
}
/
src
/
include
)
Add subdirectories; CMake processes their CMakeLists.txt files in order
add_subdirectory
(
src
)
Handle libraries and executables
add_subdirectory
(
tests
)
Handle tests
src directory CMakeLists.txt
This file defines the library target (MyLib) and the executable target (MyExecutable) and establishes their dependency.
Example
Create the static library target MyLib from two source files
add_library
(
MyLib STATIC
lib
/
module1.
cpp
lib
/
module2.
cpp
)
Specify a public header path for MyLib (PUBLIC means consumers inherit this path too)
target_include_directories
(
MyLib PUBLIC $
{
CMAKE_SOURCE_DIR
}
/
src
/
include
)
Create the executable target MyExecutable
add_executable
(
MyExecutable main.
cpp
)
Link MyLib into the executable (PRIVATE means only MyExecutable needs it)
target_link_libraries
(
MyExecutable PRIVATE MyLib
)
Difference between PRIVATE and PUBLIC:PRIVATE means the dependency is needed only by the current target,PUBLIC means the dependency is propagated to other targets that link the current target.
tests directory CMakeLists.txt
The test configuration uses the Google Test framework, so the GTest package must be found and included first.
Example
Add the following to src/CMakeLists.txt
Print a message after MyExecutable has been built
add_custom_command(
TARGET MyExecutable
POST_BUILD # Runs after the build completes
COMMAND ${CMAKE_COMMAND} -E echo "MyExecutable build complete!"
COMMENT "Print build completion message" # Description shown in the build log
)
Custom targets (add_custom_target)
A custom target is a standalone target that produces no output file and is used to perform a specific task.
Example
Add the following to src/CMakeLists.txt
Create a run target that executes the compiled program
add_custom_target
(
run
COMMAND $
{
CMAKE_BINARY_DIR
}
/
src
/
MyExecutable
DEPENDS MyExecutable
Depend on MyExecutable to make sure it is compiled first
COMMENT
"Run MyExecutable"
)
Run the custom target:
# Execute in the build directory
make run
# 或
cmake --build . --target run
Difference between custom commands and custom targets:add_custom_command attached to a target and triggered at a specific stage of that target's build;add_custom_target a standalone target that must be named explicitly to run.
Cross-platform and cross-compilation
One of CMake's core strengths is cross-platform support, making it easy to switch target platforms and architectures.
Specify the target platform
The target platform can be specified through the CMAKE_SYSTEM_NAME variable.
# Cross-compile for Linux platform
cmake -DCMAKE_SYSTEM_NAME=Linux ..
# Cross-compile for Windows platform
cmake -DCMAKE_SYSTEM_NAME=Windows ..
Use a toolchain file
For complex cross-compilation scenarios, a toolchain file is recommended to manage all platform-specific configuration in one place.
First create the toolchain file toolchain.cmake:
Example
File path: MyProject/toolchain.cmake
ARM Linux cross-compilation toolchain configuration
Specify the target system
set
(
CMAKE_SYSTEM_NAME Linux
)
set
(
CMAKE_SYSTEM_PROCESSOR arm
)
Specify the cross compiler path (adjust for your environment)
set
(
CMAKE_C_COMPILER arm
linux
gnueabihf
gcc
)
set
(
CMAKE_CXX_COMPILER arm
linux
gnueabihf
g
++
)
Specify the target system's root filesystem path (optional, used to find libraries and headers)
set
(
CMAKE_FIND_ROOT_PATH
/
path
/
to
/
arm
/
sysroot
)
Find programs only in the target sysroot (not in the host system)
set
(
CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER
)
Find library files only in the target sysroot
set
(
CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY
)
Find header files only in the target sysroot
set
(
CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY
)
Build using the toolchain file:
# Execute in the build directory
cmake -DCMAKE_TOOLCHAIN_FILE=../toolchain.cmake ..
cmake --build .
A toolchain file centralizes platform-specific compiler, linker and library path settings, so switching target platforms only requires pointing to a different toolchain file; CMakeLists.txt stays unchanged.
Build types and common options
CMake supports several build types, controlled by the CMAKE_BUILD_TYPE variable.
| Build type | Compile options | Applicable scenarios |
|---|---|---|
| Debug | -g (debug symbols) | Development and debugging, when you need breakpoints and variable inspection |
| Release | -O2 -DNDEBUG (optimization plus assertions removed) | Production release, where runtime speed matters |
| RelWithDebInfo | -O2 -g (optimization plus debug symbols) | Release builds that need profiling or debugging of optimized code |
| MinSizeRel | -Os (size optimization) | Embedded or size-sensitive scenarios |
Specify the build type:
# Debug build
cmake -DCMAKE_BUILD_TYPE=Debug ..
# Release Build
cmake -DCMAKE_BUILD_TYPE=Release ..