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 macrosMacros are predefined code snippets in programming that can be invoked with a specific name and expanded inline, typically used for code generation or to simplify repetitive tasks. and actual C++ functions:

  • A macro() command works more like a find-and-replace instruction than an actual subroutine call such as function(). Contrary to functions, macros don't create a separate entry on a call stack. This means that calling return() 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 the macro() 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 1200+ tech skills courses.