Functions, Macros & Scope
Real projects repeat themselves: every test is registered the same way, every library gets the same warning flags. CMake lets you wrap that in functions and macros, and share them through modules you include(). To use them well you need to know how variable scope works.
function() vs macro()
Both define a new command. The difference is scope:
- A function gets its own variable scope. Variables it sets disappear when it returns, unless it sets them with
PARENT_SCOPE(or usesreturn(PROPAGATE …), CMake 3.25+). - A macro is pasted into the caller, like a C preprocessor macro. Its
set()calls change the caller's variables, andreturn()inside a macro returns from the caller.
cat > scope.cmake <<'CM'
cmake_minimum_required(VERSION 3.25)
set(color "red")
function(paint_function)
set(color "green") # local to the function
set(result "from function" PARENT_SCOPE)
message(" inside function: color=${color}")
endfunction()
macro(paint_macro)
set(color "blue") # changes the caller's variable
endmacro()
function(make_version major minor)
set(version "${major}.${minor}")
return(PROPAGATE version) # CMake 3.25+: copy to the caller
endfunction()
paint_function()
message("after function: color=${color}, result=${result}")
paint_macro()
message("after macro: color=${color}")
make_version(4 4)
message("version=${version}")
CM
cmake -P scope.cmake inside function: color=green
after function: color=red, result=from function
after macro: color=blue
version=4.4
Use functions by default. Macros are only for the rare case where you really want to change the caller's scope (and even then PARENT_SCOPE is clearer).
Arguments: ARGN and cmake_parse_arguments
Named parameters are bound in order; extra arguments land in ARGN. For keyword-style commands like CMake's own (add_library(name STATIC SOURCES …)), use cmake_parse_arguments:
cat > args.cmake <<'CM'
cmake_minimum_required(VERSION 3.25)
function(add_app name)
# options (flags), one-value keywords, multi-value keywords
cmake_parse_arguments(PARSE_ARGV 1 arg "INSTALL" "OUTPUT_NAME" "SOURCES;LIBS")
if(arg_UNPARSED_ARGUMENTS)
message(FATAL_ERROR "add_app: unknown arguments ${arg_UNPARSED_ARGUMENTS}")
endif()
if(NOT arg_OUTPUT_NAME)
set(arg_OUTPUT_NAME ${name})
endif()
message("app ${name}: output=${arg_OUTPUT_NAME} sources=[${arg_SOURCES}] libs=[${arg_LIBS}] install=${arg_INSTALL}")
endfunction()
add_app(viewer SOURCES main.cpp view.cpp LIBS gfx core INSTALL)
add_app(cli OUTPUT_NAME mycli SOURCES cli.cpp)
add_app(oops SURPRISE SOURCES a.cpp)
CM
cmake -P args.cmakeapp viewer: output=viewer sources=[main.cpp;view.cpp] libs=[gfx;core] install=TRUE
app cli: output=mycli sources=[cli.cpp] libs=[] install=FALSE
CMake Error at args.cmake:7 (message):
add_app: unknown arguments SURPRISE
Call Stack (most recent call first):
args.cmake:17 (add_app)
The unknown word SURPRISE came before any keyword, so it ended up in arg_UNPARSED_ARGUMENTS and the function stopped with a clear error. (A word after a multi-value keyword such as SOURCES would simply be swallowed as one more source: keyword parsing can't catch every typo.)
The PARSE_ARGV form is the robust one: it handles empty arguments and arguments containing ; correctly. The prefix (arg) keeps the parsed variables from colliding with anything else.
Directory scope
Functions are not the only scopes. Every directory added with add_subdirectory() gets a copy of its parent's variables: it can read them, but its own set() calls stay in the subdirectory unless it uses PARENT_SCOPE. block() (3.25+) makes an explicit local scope without defining a function:
mkdir -p proj/lib && cd proj
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Scopes LANGUAGES NONE)
set(level "top")
add_subdirectory(lib)
message("top: level=${level}, lib_says=${lib_says}")
block()
set(level "inside block")
message("block: level=${level}")
endblock()
message("top again: level=${level}")
CM
cat > lib/CMakeLists.txt <<'CM'
message("lib sees level=${level}")
set(level "lib") # only changes lib's copy
set(lib_says "hello from lib" PARENT_SCOPE)
CM
cmake -S . -B build --log-level=NOTICE | grep -v '^--'lib sees level=top
top: level=top, lib_says=hello from lib
block: level=inside block
top again: level=top
Targets are different: targets are global. A target created in lib/ can be used anywhere in the project. That is one reason target-based CMake works so much better than passing variables around.
Modules and include()
Put shared functions in a .cmake file under cmake/, add that folder to CMAKE_MODULE_PATH, and include() it by name. CMake's own modules (GNUInstallDirs, CTest, CPack, FetchContent, CheckIncludeFile, …) are included the same way.
mkdir -p proj/cmake && cd proj
cat > cmake/ProjectWarnings.cmake <<'CM'
include_guard(GLOBAL) # safe to include more than once
function(enable_warnings target)
target_compile_options(${target} PRIVATE -Wall -Wextra -Wpedantic)
message("warnings enabled for ${target}")
endfunction()
CM
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Mods LANGUAGES CXX)
list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake")
include(ProjectWarnings)
include(ProjectWarnings) # include_guard makes this a no-op
add_executable(app main.cpp)
enable_warnings(app)
CM
printf 'int main() { int unused; return 0; }\n' > main.cpp
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build buildwarnings enabled for app
[1/2] Building CXX object CMakeFiles/app.dir/main.cpp.o
/home/learner/proj/main.cpp: In function ‘int main()’:
/home/learner/proj/main.cpp:1:18: warning: unused variable ‘unused’ [-Wunused-variable]
1 | int main() { int unused; return 0; }
| ^~~~~~
[2/2] Linking CXX executable app
Note that the helper sets options on a target with target_compile_options, not globally. That habit is the heart of the next sections.
Test yourself
A function calls set(x 5). What is x in the caller afterwards?
- 5
- Unchanged: the function has its own scope
- Undefined in all scopes
- An error
Why prefer function() over macro()?
- Functions are faster
- Functions have their own scope, so they don't silently overwrite the caller's variables
- Macros are deprecated
- Macros can't take arguments
A target is created inside add_subdirectory(lib). Can the parent directory link to it?
- No, it's local to lib/
- Yes, targets are global within the build
- Only with PARENT_SCOPE
- Only if lib/ calls export()