我想知道为什么 CMake 中的变量经常用美元符号和大括号括起来。例如,我看到这个电话in a CMake tutorial .
include_directories(${PROJECT_BINARY_DIR})
但根据我的尝试,这会起到同样的作用。
include_directories(PROJECT_BINARY_DIR)
什么时候需要使用 ${...}
进行换行,它是什么意思?为什么变量经常用 this 包装,即使它没有什么区别?
最佳答案
A variable reference has the form
${variable_name}
and is evaluated inside a Quoted Argument or an Unquoted Argument. A variable reference is replaced by the value of the variable, or by the empty string if the 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, the empty string, or ends in the suffix -NOTFOUND. Named boolean constants are 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/