Reputation: 899
Is there a way to have a list of variables in CMake? Specifically, what I want to do is call an existing function that takes multiple variables and checks whether they evaluate to true.
In some cases, some of those variables will be empty lists (which evaluate to false) and the function fails (as intended). But sometimes I don't even need these variables, so it would be fine if they are empty and the function should not fail due to that. Is there a way to pass some variables only in some instances?
The code I currently deal with is a CMake module to find a package:
include(FindPackageHandleStandardArgs)
# create empty list
list(APPEND mylib_LIBRARIES "")
# in some cases, the list contains elements
if(A)
list(APPEND mylib_LIBRARIES "foo")
endif(A)
# if the list mylib_LIBRARIES is empty, this will fail
find_package_handle_standard_args(mylib REQUIRED_VARS bar mylib_LIBRARIES)
If A
evaluates to true, ${mylib_LIBRARIES}
does contain content and everything is fine. Otherwise, the list is empty which evaluates to false internally and the last line gives an error.
Ideally, there would be a way to create a meta-variable that holds a list of variables that I want to pass to the function. Then, I could add mylib_LIBRARIES
only in certain cases.
Pseudo code:
include(FindPackageHandleStandardArgs)
# create empty list
list(APPEND mylib_LIBRARIES "")
# the bar variable is always used
meta_list(APPEND METALIST bar)
# in some cases add the used variable mylib_LIBRARIES to the METALIST
if(A)
list(APPEND mylib_LIBRARIES "foo")
meta_list(APPEND METALIST mylib_LIBRARIES)
endif(A)
# METALIST will contain exactly the variables that need evaluation
find_package_handle_standard_args(mylib REQUIRED_VARS ${METALIST})
Note: having multiple calls to find_package_handle_standard_args
is not practical due to combinatorical explosion.
Upvotes: 3
Views: 21214
Reputation: 65878
Your pseudo code with METALIST
variable becomes worked after simple replacement meta_list
with list
command. Also, you can delimit A
-related variables ("foo") from other ones ("bar").
BTW, it is better to initialize list-variables using set()
. This would protect from accidental collision with names in outer scope.
include(FindPackageHandleStandardArgs)
# List of variables dependent from 'A' condition.
set(A_VARS "")
if(A)
set(mylib_LIBRARIES "foo") # Other libraries can be added via list()
list(APPEND A_VARS mylib_LIBRARIES)
endif(A)
find_package_handle_standard_args(mylib REQUIRED_VARS bar ${A_VARS})
Upvotes: 7