Command Definitions: Macros
Let's learn about command definition and macros in CMake.
We'll cover the following
Command definitions
There are two ways to define our own command: we can use the macro()
command or the function()
command. The easiest way to explain the differences between these commands is by comparing them to C-style preprocessor
A
macro()
command works more like a find-and-replace instruction than an actual subroutine call such asfunction()
. Contrary to functions, macros don't create a separate entry on a call stack. This means that callingreturn()
in a macro will return to the calling statement one level higher than it would for a function (possibly terminating the execution if we're already in the top scope).The
function()
command creates a separate scope for local variables, unlike themacro()
command, which works in the variable scope of a caller. This may lead to confusing results.
Both methods accept arguments that we can name and reference inside of a command block. Additionally, CMake allows us to access arguments passed in command calls with the following references:
${ARGC}
: The count of arguments${ARGV}
: A list of all arguments${ARG0
},${ARG1}
,${ARG2}
: The value of an argument at a specific index${ARGN}
: A list of anonymous arguments that were passed by a caller after the last expected argument.
Accessing a numeric argument with an index outside of the ARGC
bounds is undefined behavior.
If we decide to define a command with named arguments, every call has to pass all of them, or it will be invalid.
Macros
Defining a macro is similar to any other block:
Get hands-on with 1400+ tech skills courses.