Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

CMake Advanced Features

CMake Advanced Features

After mastering the CMake basics, advanced features help you manage the build configuration of complex projects more flexibly.

This article covers six topics: custom modules, multi-configuration builds, advanced package lookup, custom build steps, cross-platform cross-compilation, and target property configuration.

Overall overview:

Topic Core capability Typical use cases
Custom modules and scripts Encapsulate reusable CMake logic Unified compiler options, custom lookup logic, team-shared build rules
Build configurations and targets Manage multiple configurations and multiple targets Debug/Release switching, producing multiple output artifacts
Advanced lookup and configuration Flexibly locate external dependencies Finding specific components, passing build information through configuration files
Custom build steps Extend the build workflow Code generation, resource processing, post-build automation
Cross-platform and cross-compilation Building for multiple platforms Embedded development, compiling for different operating systems
Target properties and configuration Fine-grained control of compilation and linking Setting warning levels and link paths for specific targets

Custom CMake modules and scripts

When the same logic needs to be repeated in multiple CMakeLists.txt files, encapsulating it into custom modules can greatly reduce code duplication.

The essence of custom modules and scripts is extracting commonly used CMake functions, macros and configuration into separate files for reuse across multiple projects.

Custom CMake modules

A custom module is a file with the .cmake extension that defines CMake functions and macros that can be loaded with include.

Creation steps:

Step Operation Description
1 creation cmake/ directory Create it under the project root directory to store custom modules centrally
2 Create the module file For example cmake/MyModule.cmake, and write custom functions
3 Extend the module search path Register the directory in CMakeLists.txt via CMAKE_MODULE_PATH
4 Load the module Use include() to bring in the module and call its functions

Custom module example - MyModule.cmake:

Example

File path: cmake/MyModule.cmake

Custom module: provides helper functions common to the project

Function: uniformly set compiler warning options for all targets

Parameter ARG_TARGET: the name of the target whose warnings should be set

function

(

runoob_set_warnings ARG_TARGET

)

   

Set different warning flags depending on the compiler type

   

if

(

MSVC

)

       

MSVC compiler: enable the /W4 warning level

        target_compile_options

(

$

{

ARG_TARGET

}

PRIVATE

/

W4

)

   

else

(

)

       

GCC / Clang compilers: enable common warnings

        target_compile_options

(

$

{

ARG_TARGET

}

PRIVATE

Wall

Wextra

Wpedantic

)

    endif

(

)

endfunction

(

)

Function: print basic build information for a target

function

(

runoob_print_target_info ARG_TARGET

)

    message

(

STATUS

"Target name: ${ARG_TARGET}"

)

    message

(

STATUS

"Source file list: $"

)

endfunction

(

)

Load and use the module in CMakeLists.txt:

Example

File path: CMakeLists.txt

cmake_minimum_required

(

VERSION

3.10

)

project

(

MyProject CXX

)

Add the cmake/ directory to the module search path

list

(

APPEND CMAKE_MODULE_PATH

"${CMAKE_SOURCE_DIR}/cmake"

)

Load the custom module

include

(

MyModule

)

Add an executable target

add_executable

(

MyApp main.

cpp

)

Call the custom function in the module to set warning options for MyApp

runoob_set_warnings

(

MyApp

)

Call the custom function in the module to print target information

runoob_print_target_info

(

MyApp

)

CMAKE_MODULE_PATH is the list of search paths CMake uses when looking for module files. CMake first looks in the built-in module paths, and if not found, looks in the paths specified by CMAKE_MODULE_PATH.

Using custom CMake scripts

Custom scripts are similar to modules, but are usually used to perform configuration operations rather than define reusable functions.

A script can be loaded directly with include(), and CMake executes each instruction in it in order.

Create the script file config.cmake:

Example

File path: config.cmake

Custom script: centrally manage the project's configuration options

Set the default build type to Release

if

(

NOT CMAKE_BUILD_TYPE

)

    set

(

CMAKE_BUILD_TYPE

"Release"

CACHE STRING

"Build type"

FORCE

)

    message

(

STATUS

"No build type specified, using Release by default"

)

endif

(

)

Set different compile options depending on the build type

if

(

CMAKE_BUILD_TYPE STREQUAL

"Debug"

)

    message

(

STATUS

"Enable Debug mode: disable optimization, enable debug symbols"

)

else

(

)

    message

(

STATUS

"Enable Release mode: enable O2 optimization"

)

endif

(

)

Call the script in CMakeLists.txt:



# Load script using absolute path

include(${CMAKE_SOURCE_DIR}/config.cmake)


Build configurations and targets

CMake supports managing multiple build configurations (such as Debug and Release) in the same project and defining multiple build targets.

Multi-configuration generators

Different CMake generators handle configurations differently.

Multi-configuration generators such as Visual Studio and Xcode allow switching Debug/Release within the same build directory, while single-configuration generators such as Unix Makefiles need the build type fixed at configuration time.

Generator type Typical generators How the configuration is specified
Single configuration Unix Makefiles, Ninja At configuration time via -DCMAKE_BUILD_TYPE=Release specified
Multi configuration Visual Studio, Xcode At build time via --config Release switch

Set the default configuration in CMakeLists.txt:



# Only effective for single configuration generator, multi-configuration generator will ignore this variable

set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Build type")

CMAKE_BUILD_TYPE only applies to single-configuration generators. If you use Visual Studio, switch configurations with cmake --build . --config Release or in the IDE.

Build targets

Multiple build targets can be defined in one CMake project, each with its own compile options and link dependencies.

This lets you produce multiple executables or multiple libraries in a single build.

Example

Define two executable targets, each with different source files

add_executable

(

MyApp src

/

main.

cpp

)

add_executable

(

MyTool src

/

tool.

cpp

)

Set different compile macros for different targets to control conditional compilation

set_target_properties

(

MyApp PROPERTIES COMPILE_DEFINITIONS

"APP_MODE"

)

set_target_properties

(

MyTool PROPERTIES COMPILE_DEFINITIONS

"TOOL_MODE"

)

Link different libraries for different targets

target_link_libraries

(

MyApp PRIVATE MyLib

)

target_link_libraries

(

MyTool PRIVATE MyLib CLI11

::

CLI11

)


Advanced lookup and configuration

Beyond basic find_package usage, CMake also supports specifying components, precise version control, and passing build information through configuration file templates.

Advanced find_package usage

The COMPONENTS keyword lets you find only specific submodules of a library instead of the whole package.

This matters a lot for large libraries like Boost: importing only what you need avoids linking unused components.

Example

Find only the filesystem and system components of Boost (not all of Boost)

filesystem depends on system internally, so both must be declared

find_package

(

Boost REQUIRED COMPONENTS filesystem

system

)

Check whether the required components were found

if

(

Boost_FOUND

)

    message

(

STATUS

"Boost version: ${Boost_VERSION}"

)

    message

(

STATUS

"Boost header path: ${Boost_INCLUDE_DIRS}"

)

   

Link each required component separately

    target_link_libraries

(

MyApp PRIVATE

        Boost

::

filesystem

        Boost

::

system

   

)

endif

(

)

Specify a search path (for non-standard install locations):



# Method one: Specify the root directory via a variable

cmake .. -DBOOST_ROOT=/path/to/custom/boost



# Method two: Pre-setting in CMakeLists.txt

set(BOOST_ROOT "/path/to/custom/boost")

find_package(Boost REQUIRED COMPONENTS filesystem)

Configuration files and build options

The configure_file() command injects CMake variable values into source files, passing configuration information at compile time.

This is very useful when version numbers, build timestamps and similar information must be compiled into the program.

Create the configuration template file config.h.in:

Example

// File path: config.h.in

// CMake configuration template file; configure_file() generates config.h from it

// Project version number (replaced by the CMake variable @PROJECT_VERSION@)

#define RUNOOB_VERSION "@PROJECT_VERSION@"

// Build type (Debug or Release)

#define RUNOOB_BUILD_TYPE "@CMAKE_BUILD_TYPE@"

// Build timestamp

#define RUNOOB_BUILD_TIMESTAMP "@BUILD_TIMESTAMP@"

Configure and generate the header in CMakeLists.txt:

Example

Get the current timestamp and store it in a variable

string

(

TIMESTAMP BUILD_TIMESTAMP

"%Y-%m-%d %H:%M:%S"

)

Replace @VARIABLE@ in config.h.in with the CMake variable value

Output to config.h in the build directory

configure_file

(

config.

h

.

in

config.

h

)

Add the build directory to the header search path so source files can find config.h

include_directories

(

$

{

CMAKE_BINARY_DIR

}

)

Use the generated configuration in source files:



// Include the generated configuration file in main.cpp

#include "config.h"



std::cout << "RUNOOB Version: " << RUNOOB_VERSION << std::endl;

std::cout << "Build Type: " << RUNOOB_BUILD_TYPE << std::endl;


Generate custom build steps

Besides standard compiling and linking, CMake lets you insert custom actions into the build, such as code generation, resource copying and post-build notifications.

Custom commands

add_custom_command() defines a custom command that runs when a certain file needs updating.

The core idea is dependency driven: the command runs only when the OUTPUT file is missing or a DEPENDS file changes.

Example

Custom command: generate code from a template file

Run only when generated_file.cpp does not exist or input_template.txt changes

add_custom_command

(

   

Output file (CMake checks this file to decide whether to rerun the command)

    OUTPUT $

{

CMAKE_BINARY_DIR

}

/

generated_file.

cpp

   

Command to run (here cmake -E performs a built-in file generation operation)

    COMMAND $

{

CMAKE_COMMAND

}

       

E echo

"// Auto-generated source file"

$

{

CMAKE_BINARY_DIR

}

/

generated_file.

cpp

   

Dependency file (the command reruns when this file changes)

    DEPENDS $

{

CMAKE_SOURCE_DIR

}

/

input_template.

txt

   

Message printed while running

    COMMENT

"Generating source file from template..."

)

Trigger the command during the build phase, after linking completes:

Example

After MyApp is built, copy the executable to the deployment directory

add_custom_command

(

    TARGET MyApp POST_BUILD

    COMMAND $

{

CMAKE_COMMAND

}

E copy

        $

<

TARGET_FILE

:

MyApp

        $

{

CMAKE_SOURCE_DIR

}

/

deploy

/

    COMMENT

"Copy MyApp to the deployment directory"

)

Custom targets

add_custom_target() defines a build target that produces no output file; it is typically used to group several custom commands together.

Unless the ALL keyword is used, a custom target is not built by default and must be named explicitly.

Example

Custom target: associate the custom command defined above

ALL means it runs automatically during the default build (make)

add_custom_target

(

generate_code ALL

   

Depends on the OUTPUT file defined earlier

    DEPENDS $

{

CMAKE_BINARY_DIR

}

/

generated_file.

cpp

)

Custom target: perform an auxiliary task (not run in the default build)

add_custom_target

(

deploy

    COMMAND $

{

CMAKE_COMMAND

}

E echo

"Deploying to server..."

    COMMAND $

{

CMAKE_COMMAND

}

E copy_directory

        $

{

CMAKE_BINARY_DIR

}

/

bin

       

/

opt

/

runoob

/

deploy

/

    COMMENT

"Perform deployment"

)

Trigger this target separately at build time

$ cmake --build . --target deploy

Difference between add_custom_command and add_custom_target: the former defines a rule for "how to generate a file", triggered by dependencies; the latter defines an action target for "what to do", which must be called explicitly or run automatically with ALL.


Cross-platform and cross-compilation

One of CMake's core strengths is cross-platform support: the same CMakeLists.txt can generate build files for different operating systems and architectures.

Cross-platform building

CMake automatically detects the current platform's compiler and system environment and generates matching build files.

You can also specify target platform information explicitly through variables.

Variables Purpose Example value
CMAKE_SYSTEM_NAME Target operating system Linux, Windows, Darwin, Android
CMAKE_SYSTEM_PROCESSOR Target processor architecture x86_64. arm, aarch64
CMAKE_C_COMPILER C compiler path /usr/bin/arm-linux-gnueabihf-gcc
CMAKE_CXX_COMPILER C++ compiler path /usr/bin/arm-linux-gnueabihf-g++

Cross compilation

Cross compilation means compiling on one platform (for example x86_64 Linux) a program that runs on another architecture (for example ARM).

CMake uses a toolchain file to specify the compilers, system information and linker configuration needed for cross compilation.

Create the toolchain file toolchain.cmake:

Example

File path: toolchain.cmake

ARM Linux cross-compilation toolchain configuration file

The target system is Linux

set

(

CMAKE_SYSTEM_NAME Linux

)

The target processor architecture is ARM

set

(

CMAKE_SYSTEM_PROCESSOR arm

)

Specify the cross compiler (required: adjust the path to your actual toolchain location)

set

(

CMAKE_C_COMPILER

/

usr

/

bin

/

arm

linux

gnueabihf

gcc

)

set

(

CMAKE_CXX_COMPILER

/

usr

/

bin

/

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

)

When finding programs, search only in the target system paths (not in host paths)

set

(

CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER

)

When finding libraries, search only in the target system paths

set

(

CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY

)

When finding headers, search only in the target system paths

set

(

CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY

)

Cross compile using the toolchain file:



# Specify the toolchain file using -DCMAKE_TOOLCHAIN_FILE during configuration

mkdir build_arm && cd build_arm

cmake -DCMAKE_TOOLCHAIN_FILE=../toolchain.cmake ..



# Compile using the generated Makefile (will call the ARM cross-compiler)

make

The toolchain file must be specified on the first cmake run. If CMakeCache.txt already exists, delete the build directory and reconfigure before switching toolchains.


Target properties and configuration

CMake lets you control compile options, link options and various properties at the target level, which is the recommended practice in modern CMake.

Target properties

set_target_properties() sets properties at the target level; these properties affect compiler and linker behavior.

property Purpose Example
COMPILE_OPTIONS Set compile options -Wall, -O2
COMPILE_DEFINITIONS Set preprocessor macros DEBUG, VERSION=2
LINK_FLAGS Set linker flags -L/path/to/lib
OUTPUT_NAME Change the output file name The target name is MyApp and the output is my_app

Example

Create the executable target

add_executable

(

MyApp main.

cpp

)

Set compile options and link flags for the target

set_target_properties

(

MyApp PROPERTIES

    COMPILE_OPTIONS

"-Wall;-Wextra"

    COMPILE_DEFINITIONS

"RUNOOB_DEBUG"

    LINK_FLAGS

"-L/usr/local/lib"

    OUTPUT_NAME

"my_app"

)

The set_target_properties call above is equivalent to the following three commands:

target_compile_options(MyApp PRIVATE -Wall -Wextra)

target_compile_definitions(MyApp PRIVATE RUNOOB_DEBUG)

target_link_options(MyApp PRIVATE -L/usr/local/lib)

In modern CMake, prefer target_compile_options(), target_compile_definitions() and target_link_options() over set_target_properties(), because they support PUBLIC/PRIVATE/INTERFACE visibility control and make dependencies clearer.

Custom compile and link options

The target_* commands give more precise control over how options propagate.

Example

Set compile options for MyApp

PRIVATE: only MyApp itself uses these options when compiling

target_compile_options

(

MyApp PRIVATE

Wall

Wextra

Wpedantic

)

Set preprocessor definitions for MyApp

Equivalent to writing #define RUNOOB_VERSION "1.0" in a source file

target_compile_definitions

(

MyApp PRIVATE RUNOOB_VERSION

=

"1.0"

)

Set link options for MyApp

target_link_options

(

MyApp PRIVATE

L

/

usr

/

local

/

lib

)

For a library, PUBLIC lets targets linking it inherit these options too

For example: any target using MyLib will automatically enable C++17

target_compile_features

(

MyLib PUBLIC cxx_std_17

)


Notes

CMAKE_BUILD_TYPE only works with single-configuration generators.If the project must support both Makefile and Visual Studio, do not rely on the value of CMAKE_BUILD_TYPE. Use generator expressions $<$:DEBUG_VALUE> to switch dynamically according to the actual configuration.

Prefer the target_xxx family of commands.set_target_properties is powerful but lacks visibility control. Where PUBLIC/PRIVATE/INTERFACE semantics are needed, dedicated commands such as target_compile_options are the better choice.

The toolchain file must be specified on the first cmake run.When cross compiling, re-specifying a toolchain in a directory that already has CMakeCache.txt can produce an incomplete configuration. Always configure cross compilation in a clean build directory.

Prefix function names in custom modules.Avoid naming conflicts with built-in CMake commands or other modules. For example, use the project name as a prefix: myproject_set_warnings().