【问题标题】:What's the evaluated value of <string> in if(<string>) in CMake?CMake 中 if(<string>) 中 <string> 的评估值是多少?
【发布时间】:2020-04-13 12:22:52
【问题描述】:

我的 hello.txt

cmake_policy(SET CMP0054 NEW)

set(VAR ON)

# VAR will be treated as a string
if("VAR")
  message(TRUE)
else()
  message(FALSE)
endif()

# output prints FALSE

来自政策 CMP0054:

为了防止歧义,可以在带引号的参数或括号参数中指定潜在的变量或关键字名称。带引号或括号的变量或关键字将被解释为字符串,不会被取消引用或解释。请参阅政策 CMP0054。

CMake 文档没有提到 if(&lt;string&gt;):

if(&lt;variable|string&gt;)

如果给定一个定义为非假常量值的变量,则为真。否则为假。 (注意宏参数不是变量。)

为什么非空字符串的计算结果为FALSE

【问题讨论】:

  • 在文档中,False otherwise 似乎给出了答案?将非空字符串视为 false 的行为很奇怪。

标签: cmake cmake-language


【解决方案1】:

您在documentation 中寻找正确的地方:

if(&lt;variable|string&gt;)

如果给定一个定义为非假常量值的变量,则为真。否则为假。 (注意宏参数不是变量。)

但是,文档并不完整,因为没有明确提及 &lt;string&gt; 案例。仅包含字符串的 CMake if 语句的行为与此处针对变量描述的行为不同。字符串的文档应为:

如果给定的字符串与真常量(1ONYESTRUEY 或非零数字)匹配,则为真。否则为假。

换句话说,任何与这些 CMake true 常量之一不匹配的字符串都将评估为 False。正如您已经指出的,字符串"VAR":

if ("VAR")
  message(TRUE)
else()
  message(FALSE)
endif()

打印FALSE。但是,作为字符串的真正常量(比如说"y"):

if ("y")
  message(TRUE)
else()
  message(FALSE)
endif()

打印TRUE

此逻辑可在 CMake source code 中的一个名为 GetBooleanValue() 的函数中验证:

bool cmConditionEvaluator::GetBooleanValue(
  cmExpandedCommandArgument& arg) const
{
  // Check basic constants.
  if (arg == "0") {
    return false;
  }
  if (arg == "1") {
    return true;
  }

  // Check named constants.
  if (cmIsOn(arg.GetValue())) {
    return true;
  }
  if (cmIsOff(arg.GetValue())) {
    return false;
  }

  // Check for numbers.
  if (!arg.empty()) {
    char* end;
    double d = strtod(arg.c_str(), &end);
    if (*end == '\0') {
      // The whole string is a number.  Use C conversion to bool.
      return static_cast<bool>(d);
    }
  }

  // Check definition.
  const char* def = this->GetDefinitionIfUnquoted(arg);
  return !cmIsOff(def);
}

【讨论】:

  • 非常感谢!源代码一目了然!我的博客guihao-liang.github.io/2020-01-04-cmake-101 上也有一个帖子,我没有阅读源代码,但猜测了内部逻辑来评估条件。我会用你的答案更新我的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 2013-03-24
  • 1970-01-01
  • 2017-08-22
  • 2017-10-27
  • 1970-01-01
相关资源
最近更新 更多