gpt4 book ai didi

cmake - CMake 中的变量列表

转载 作者:行者123 更新时间:2023-12-05 01:20:36 30 4
gpt4 key购买 nike

有没有办法在 CMake 中得到一个变量列表?具体来说,我想要做的是调用一个现有函数,该函数接受多个变量并检查它们的计算结果是否为 true

在某些情况下,其中一些变量将是空列表(计算结果为 false)并且函数会失败(如预期的那样)。但有时我什至不需要这些变量,所以如果它们为空就好了,函数不应该因此而失败。有没有办法只在某些情况下传递一些变量?

我目前处理的代码是一个用于查找包的 CMake 模块:

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)

如果 A 的计算结果为真,则 ${mylib_LIBRARIES} 确实包含内容并且一切正常。否则,列表为空,在内部评估为 false 并且最后一行给出错误。

理想情况下,有一种方法可以创建一个元变量,其中包含我要传递给函数的变量列表。然后,我可以仅在某些情况下添加 mylib_LIBRARIES

伪代码:

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

注意:由于组合爆炸,多次调用 find_package_handle_standard_args 是不切实际的。

最佳答案

在用 list 命令简单替换 meta_list 后,你的带有 METALIST 变量的伪代码就可以工作了。此外,您可以将 A 相关变量(“foo”)与其他变量(“bar”)分隔开。

顺便说一句,最好使用set() 来初始化列表变量。这将防止与外部范围内的名称发生意外冲突。

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

关于cmake - CMake 中的变量列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31450133/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com