Get a list of variables with a specified prefix

2020-06-17 14:20发布

问题:

Is there a way to get a list of user-defined variables that have a specified prefix? For example:

set(vars_MyVar1 something)
set(vars_MyVar2 something)
getListOfVarsStartingWith(vars_)

?

回答1:

The function getListOfVarsStartingWith can be written in the following way:

function (getListOfVarsStartingWith _prefix _varResult)
    get_cmake_property(_vars VARIABLES)
    string (REGEX MATCHALL "(^|;)${_prefix}[A-Za-z0-9_]*" _matchedVars "${_vars}")
    set (${_varResult} ${_matchedVars} PARENT_SCOPE)
endfunction()

The functions uses the CMake function string(REGEX MATCHALL to compute all matched variable names without a loop. Here is a usage example:

set(vars_MyVar1 something)
set(vars_MyVar2 something)
getListOfVarsStartingWith("vars_" matchedVars)
foreach (_var IN LISTS matchedVars)
    message("${_var}=${${_var}}")
endforeach()

If the search should only return cache variables, use the following function:

function (getListOfVarsStartingWith _prefix _varResult)
    get_cmake_property(_vars CACHE_VARIABLES)
    string (REGEX MATCHALL "(^|;)${_prefix}[A-Za-z0-9_]*" _matchedVars "${_vars}")
    set (_resultVars "")
    foreach (_variable ${_matchedVars})
        get_property(_type CACHE "${_variable}" PROPERTY TYPE)
        if (NOT "${_type}" STREQUAL "STATIC") 
            list (APPEND _resultVars "${_variable}")
        endif()
    endforeach()
    set (${_varResult} ${_resultVars} PARENT_SCOPE)
endfunction()

This function queries the CACHE_VARIABLES property and also makes sure that cache variables of type STATIC, which are used by CMake internally, are not returned.



回答2:

I don't know any function to do that, but you can easily build one yourself by requesting all defined variables with GET_CMAKE_PROPERTY and then filtering the list with a regex.

For example:

SET(my_prefix_var1 "bob1")
SET(my_prefix_var2 "bob2")

# Get all variables
GET_CMAKE_PROPERTY(vars VARIABLES)

# Filter by prefix and build the "res" list
FOREACH(var ${vars})
    STRING(REGEX MATCH "^my_prefix" item ${var})
    IF(item)
        LIST(APPEND res ${var})
    ENDIF(item)
ENDFOREACH(var)


标签: cmake