C++ CMake Cheat Sheet
Covers CMakeLists.txt basics, target-based library linking, common build-system variables, and the CLI workflow for configuring and building.
2 PagesIntermediateApr 5, 2026
Minimal CMakeLists.txt
The smallest project file to build an executable.
cmake
cmake_minimum_required(VERSION 3.20)project(MyApp VERSION 1.0 LANGUAGES CXX)set(CMAKE_CXX_STANDARD 17)set(CMAKE_CXX_STANDARD_REQUIRED ON)add_executable(myapp main.cpp src/helper.cpp)target_include_directories(myapp PRIVATE include)
Libraries & Linking
Build a library and link it into an executable target.
cmake
add_library(mathutils STATIC src/mathutils.cpp)target_include_directories(mathutils PUBLIC include)add_executable(myapp main.cpp)target_link_libraries(myapp PRIVATE mathutils)# Find and link an external packagefind_package(ZLIB REQUIRED)target_link_libraries(myapp PRIVATE ZLIB::ZLIB)# Fetch a dependency at configure time (CMake 3.14+)include(FetchContent)FetchContent_Declare(fmt GIT_REPOSITORY https://github.com/fmtlib/fmt.git GIT_TAG 10.1.1)FetchContent_MakeAvailable(fmt)target_link_libraries(myapp PRIVATE fmt::fmt)
Configure & Build (CLI)
Out-of-source build workflow from the command line.
bash
cmake -S . -B build # configure into ./buildcmake -B build -DCMAKE_BUILD_TYPE=Release # set build typecmake --build build # build (calls make/ninja under the hood)cmake --build build --target myapp -j 8 # build a specific target, 8 jobsctest --test-dir build # run tests registered via enable_testing()cmake --install build --prefix /usr/local # install
Common Variables & Commands
Frequently used CMake variables and directives.
- CMAKE_BUILD_TYPE- Debug, Release, RelWithDebInfo, or MinSizeRel; controls optimization/debug flags.
- CMAKE_CXX_STANDARD- Sets the required C++ standard, e.g. 17 or 20.
- target_link_libraries- Links a library to a target; scope keyword PRIVATE/PUBLIC/INTERFACE controls propagation to dependents.
- target_include_directories- Adds header search paths to a target with the same PRIVATE/PUBLIC/INTERFACE scoping.
- add_subdirectory- Includes another directory's CMakeLists.txt, e.g. for a nested library or test folder.
- enable_testing / add_test- Registers tests runnable via ctest.
Pro Tip
Always prefer target_* commands (target_include_directories, target_link_libraries, target_compile_definitions) with PUBLIC/PRIVATE/INTERFACE scoping over the old global include_directories()/link_libraries() - it keeps usage requirements properly scoped as your dependency graph grows.
Was this cheat sheet helpful?
Explore Topics
#CCMake#CCMakeCheatSheet#Programming#Intermediate#MinimalCMakeListsTxt#LibrariesLinking#ConfigureBuildCLI#CommonVariablesCommands#CommandLine#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance