Search code examples
macroscmakedefinitions

How to define a CMake macro in terms of another one?


How to define a CMake macro in terms of another one?

add_definitions(-DMACRO1=1)
add_definitions(-DMACRO2=2)

add_definitions(-DMACRO3=${MACRO1})   # no effect

message( "COMPILE_DEFINITIONS = ${DirDefs}" )

This is the output I would like:

COMPILE_DEFINITIONS = MACRO1=1;MACRO2=2;MACRO3=1

This is what I get:

COMPILE_DEFINITIONS = MACRO1=1;MACRO2=2;MACRO3=

Solution

  • Calling add_definitions(-DMACRO1=1) simply adds this definition to your compiler's command-line. Its value is equivalent to a #define directive in your source code. It does not create a CMake variable.

    So, in your case,${MACRO1} evaluates to the empty string, resulting in

    ADD_DEFINITIONS(-DMACRO3=)
    

    To make it work, use SET(...) to define the variable in CMake:

    set(MACRO1 1)
    add_definitions(-DMACRO1=${MACRO1})
    add_definitions(-DMACRO2=2)
    
    add_definitions(-DMACRO3=${MACRO1})
    
    message( "COMPILE_DEFINITIONS = ${DirDefs}" )