gpt4 book ai didi

cmake - 我什么时候应该在 CMake 中用 ${...} 包装变量?

转载 作者:行者123 更新时间:2023-12-01 19:36:55 28 4
gpt4 key购买 nike

我想知道为什么 CMake 中的变量经常用美元符号和大括号括起来。例如,我看到这个电话in a CMake tutorial .

include_directories(${PROJECT_BINARY_DIR})

但根据我的尝试,这会起到同样的作用。

include_directories(PROJECT_BINARY_DIR)

什么时候需要使用 ${...} 进行换行,它是什么意思?为什么变量经常用 this 包装,即使它没有什么区别?

最佳答案

引用the CMake documentation :

A variable reference has the form ${variable_name} and is evaluatedinside a Quoted Argument or an Unquoted Argument. A variable referenceis replaced by the value of the variable, or by the empty string ifthe variable is not set.

换句话说,写 PROJECT_BINARY_DIR从字面上看,指的是字符串“PROJECT_BINARY_DIR”。将其封装在${...}中为您提供名为 PROJECT_BINARY_DIR 的变量的内容。

考虑:

set(FOO "Hello there!")
message(FOO) # prints FOO
message(${FOO}) # prints Hello there!

正如您可能已经猜到的那样,include_directories(PROJECT_BINARY_DIR)只是尝试将名称为 PROJECT_BINARY_DIR 的子目录添加到包含目录中。在大多数构建系统上,如果不存在这样的目录,它将简单地忽略该命令,这可能会让您产生它按预期工作的印象。

一个常见的混淆来源是 if()不需要显式取消引用变量:

set(FOO TRUE)
if(FOO)
message("Foo was set!")
endif()

再次the documentation explains this behavior :

if(<constant>)

True if the constant is 1, ON, YES, TRUE, Y, or a non-zero number. False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, theempty string, or ends in the suffix -NOTFOUND. Named boolean constantsare case-insensitive. If the argument is not one of these constants,it is treated as a variable.

if(<variable>)

True if the variable is defined to a value that is not a false constant. False otherwise. (Note macro arguments are not variables.)

特别是,人们可以想出一些奇怪的例子,例如:

unset(BLA)
set(FOO "BLA")
if(FOO)
message("if(<variable>): True")
else()
message("if(<variable>): False")
endif()
if(${FOO})
message("if(<constant>): True")
else()
message("if(<constant>): False")
endif()

这将采取 TRUE变量 case 中的分支,以及 FALSE常量情况下的分支。这是因为在常量情况下,CMake 会去寻找变量 BLA执行检查(未定义,因此我们最终处于 FALSE 分支)。

关于cmake - 我什么时候应该在 CMake 中用 ${...} 包装变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25809332/

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