Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

cmake invoking dynamic macro name

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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})
")
        endif()
        include("${_helper}")
    endif()
endfunction()

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...