Get a list of variables with a specified prefix
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.