cmake

Functions and Macros

Remarks#

The main difference between macros and functions is, that macros are evaluated within the current context, while functions open a new scope within the current one. Thus, variables defined within functions are not known after the function has been evaluated. On the contrary, variables within macros are still defined after the macro has been evaluated.

Simple Macro to define a variable based on input

macro(set_my_variable _INPUT)
  if("${_INPUT}" STREQUAL "Foo")
    set(my_output_variable "foo")
  else()
    set(my_output_variable "bar")
  endif()
endmacro(set_my_variable)

Use the macro:

set_my_variable("Foo")
message(STATUS ${my_output_variable})

will print

-- foo

while

set_my_variable("something else")
message(STATUS ${my_output_variable})

will print

-- bar

Macro to fill a variable of given name

macro(set_custom_variable _OUT_VAR)
  set(${_OUT_VAR} "Foo")
endmacro(set_custom_variable)

Use it with

set_custom_variable(my_foo)
message(STATUS ${my_foo})

which will print

-- Foo

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow