In CMake, a team's add_library wrapper is written as a macro; what breaks compared with a function, and when is a macro still the right choice?
answer
- pasted in place versus called
- temporaries leak into the caller
- ARGN is text, not a variable
- return() leaves the caller
- macro when you mean caller scope
basics
~20 sA macro's body is substituted into the caller, so its temporaries leak, ARGN and ARGV are text rather than variables, and return() exits the caller. A function gets its own scope. Use a macro only when setting variables in the caller is the point.
solid answer
~40 sA `function()` call runs in a **new variable scope**, and `ARGN`, `ARGC`, `ARGV` and `ARGV0`... are real variables; results go back with `set(... PARENT_SCOPE)` or `return(PROPAGATE ...)`. A `macro()` call behaves as if its body were pasted at the call site after text substitution of `${ARGN}`, `${name}` and friends. So every temporary it sets lands in the caller's scope; `if(ARGN)` and `foreach(x IN LISTS ARGN)` see a real variable named `ARGN` (the caller's, if any) instead of the macro's arguments; even `\${ARGN}` gets substituted; and `return()` returns from the **caller**. For an `add_library` wrapper all of that is a liability, and since targets are global, a function loses nothing. A macro fits when altering the caller's variables is the job, such as a helper that sets several result variables directly.
code
cmake · 21 linesmacro(engine_lib_m name)
set(_kind STATIC)
if(ARGN)
message(STATUS "macro ${name}: if(ARGN) true")
else()
message(STATUS "macro ${name}: if(ARGN) false, ARGN text=[${ARGN}]")
endif()
endmacro()
function(engine_lib_f name)
set(_kind STATIC)
if(ARGN)
message(STATUS "function ${name}: if(ARGN) true, ARGN=[${ARGN}]")
endif()
endfunction()
engine_lib_m(core SHARED)
message(STATUS "after macro: _kind=[${_kind}]")
unset(_kind)
engine_lib_f(core SHARED)
message(STATUS "after function: _kind=[${_kind}]")go deeper
Recall that a CMake function has its own variable scope while a macro runs in the caller's scope.
Explain that macro arguments are text replacements, so if(ARGN) and foreach over ARGN behave unexpectedly, and how PARENT_SCOPE returns values.
Diagnose leaked variables and early returns traced to a macro, and convert wrappers to functions, knowing targets stay global.
Set a team default of functions for helpers, with macros reserved for deliberate caller-scope effects and documented as such.
## Two ways to define a command CMake lets a project define its own commands with `function(<name> ...)` and `macro(<name> ...)`. Both are invoked like built-in commands, case-insensitively, and both can take named parameters plus extra arguments. The CMake documentation names two important differences: **how arguments exist** and **how control flows**. | Aspect | `function()` | `macro()` | |---|---|---| | Variable scope | New scope per call | Caller's scope | | `ARGN`, `ARGC`, `ARGV`, `ARGV0`... | Real variables | Text replacements | | `return()` | Leaves the function | Leaves the **caller** | | `CMAKE_CURRENT_FUNCTION` and related variables | Set | Not set | | `cmake_parse_arguments(PARSE_ARGV ...)` | Allowed | Not allowed | ## What goes wrong in a macro wrapper A wrapper like `engine_lib_m(core SHARED)` written as a macro showed all of these under CMake 4.4.4: 1. **Leaking temporaries.** The macro ran `set(_kind STATIC)`; after the call the caller's `${_kind}` was `STATIC`. The same code as a function left it unset. Leaked names collide with the caller's own variables, and the order of calls starts to matter. 2. **`if(ARGN)` is false even with arguments.** In a macro `ARGN` is not a variable, so `if(ARGN)` looks for a real variable called `ARGN` and found none. The documented workaround is `if(${ARGC} GREATER 1)` or copying `${ARGN}` into a real variable first. 3. **Picking up the caller's `ARGN`.** The documentation's example: a macro doing `foreach(arg IN LISTS ARGN)`, called from inside a function that received `a b c`, loops over the **function's** `a;b;c`, not the macro's own arguments. 4. **Substitution ignores escaping.** A macro body containing `"\${ARGN}"` in a message still had `${ARGN}` replaced by the argument text before the command ran, producing `Invalid character escape '\S'` for an argument `SHARED`. 5. **`return()` exits the caller.** A macro that calls `return()` from inside a function ended that function: the line after the macro call never ran. None of these are bugs. They are the documented consequence of a macro being text substitution, and the documentation itself recommends avoiding `return()` in macros entirely. ## Why a function costs nothing for an add_library wrapper Targets are not variables. A target created by `add_library()` inside a function exists globally after the call, with all its properties and usage requirements, so the wrapper's real output survives the function's scope. Only plain variables need to be returned, and a wrapper rarely needs any; when it does: - `set(${out_var} "${value}" PARENT_SCOPE)` writes into the caller's scope, while the function's own copy stays as it was. - `return(PROPAGATE out_var)` (CMake 3.25, policy CMP0140) propagates the named variables when the function returns, through any `block()` inside it. - Passing the **name** of the output variable as a parameter keeps the caller in control of naming. ## When a macro is still right - **Setting variables in the caller is the purpose.** A helper that computes and sets several values directly, such as a set of compiler-specific flags, avoids a `PARENT_SCOPE` line per variable. Name the temporaries with a unique prefix and `unset()` them at the end. - **Calling commands whose results should land in the caller.** `find_package()` and `include()` set variables in the scope where they run; inside a macro those variables reach the caller, inside a function they stay local unless forwarded. - **Legacy code.** Older helpers written as macros can stay until they are touched, but convert them when they grow `return()`, `ARGN` tests or temporaries. ## Converting a macro wrapper to a function 1. Change `macro`/`endmacro` to `function`/`endfunction`; the call sites do not change. 2. Replace `if(${ARGC} GREATER 1)`-style tests with ordinary `if(ARGN)` or, better, `cmake_parse_arguments(PARSE_ARGV ...)`. 3. Find every variable the caller relied on after the call and return it explicitly with `PARENT_SCOPE` or `return(PROPAGATE ...)`. 4. Re-run the configure and compare `cmake -LA` output and the generated build files before and after, to catch a leaked variable something depended on. ## Practical rules 1. Default to `function()` for any wrapper or helper. 2. In a macro, never use `return()`, and test optional arguments with `${ARGC}` rather than `if(ARGV1)` or `if(DEFINED ARGV2)`. 3. Give macro temporaries and `cmake_parse_arguments` prefixes a name unique to the macro. 4. Keep the case you defined: invocation is case-insensitive, but the documentation recommends calling it as defined, conventionally all lowercase.
- How does a CMake function return a value to its caller?It sets a variable in the caller's scope with `set(<name> <value> PARENT_SCOPE)`, usually with the variable's name passed in as a parameter. Since CMake 3.25, `return(PROPAGATE <name>...)` does the same when the function returns, which also works through any `block()` inside the function. Targets and their properties need no returning: they are global once created.
- In a macro, how do you safely test whether an optional second argument was passed?Use `if(${ARGC} GREATER 1)`. In a macro, `ARGC` and `ARGV1` are text replacements, so `if(ARGC GREATER 1)` and `if(DEFINED ARGV1)` look for real variables of those names and give the wrong answer. `${ARGC}` is replaced with the actual count before `if()` runs.
A macro is like pasting a recipe's steps into your own notebook, so its scribbles end up on your pages; a function is like handing the recipe to a cook in another kitchen, who sends back only the dish you asked for.
- Thinks macros and functions differ only in naming convention
- Expects return() in a macro to end only the macro
- Writes if(ARGN) inside a macro to test for extra arguments
- Believes targets created inside a function vanish when it returns
- Thinks PARENT_SCOPE also updates the function's own copy