Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of variables with a specified prefix

Tags:

cmake

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_)

?

like image 395
David Doria Avatar asked Sep 20 '12 21:09

David Doria


1 Answers

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.

like image 143
sakra Avatar answered Nov 04 '22 21:11

sakra