cmake invoking dynamic macro name

2019-01-29 04:50发布

问题:

I have a two macro names, for example:

macro(my_macro1)
# stuff only to use in this macro
endmacro()

macro(my_macro2)
# stuff only to use in this macro
endmacro()

I'd like to dynamic call the macros based a variable name, for example:

if (...)
set (ver 1)
else ()
set (ver 2)
endif ()
my_macro${ver} # this is my idea

Any help?

回答1:

As @Tsyvarev has commented CMake doesn't support dynamic function names. So here are some alternatives:

Simple Approach

macro(my_macro ver)
    if(${ver} EQUAL 1)
        my_macro1()
    elseif(${ver} EQUAL 2)
        my_macro2()
    else()
        message(FATAL_ERROR "Unsupported macro")
    endif()
endmacro()

set(ver 1)
my_macro(ver)
set(ver 2)
my_macro(ver)

A call() Function Implementation

Building on @Fraser work here is a more generic call() function implementation:

function(call _id)
    if (NOT COMMAND ${_id})
        message(FATAL_ERROR "Unsupported function/macro \"${_id}\"")
    else()
        set(_helper "${CMAKE_BINARY_DIR}/helpers/macro_helper_${_id}.cmake")
        if (NOT EXISTS "${_helper}")
            file(WRITE "${_helper}" "${_id}(\$\{ARGN\})\n")
        endif()
        include("${_helper}")
    endif()
endfunction()

set(ver 1)
call(my_macro${ver})
set(ver 2)
call(my_macro${ver})


标签: cmake