为什么 CMake 语法到处都有多余的括号?

Why does CMake syntax have redundant parentheses everywhere?

CMake 的 if 是这样的:

if (condition)
    ...
else if (...)
    ...
else (...)
    ...
endif (...)

对于 else if (...)(...) 测试单独的条件。
为什么 else (...) 而不仅仅是 else?为什么是 endif (...) 而不是 endif


Cmake 的函数是这样的:

function(funcname ...)
    ...
endfunction(funcname ...)

为什么 endfunction(funcname ...) 而不是 endfunction


我可以省略出现的多余括号的内容,例如:endif ()。这个构造的目的是什么?

我相信最初的意图是,通过在每个子句(例如,else 语句)中重复初始表达式(例如,if 语句中的那个),它将使更清楚哪个语句实际上被关闭了,解析器可以验证并警告没有发生任何错误。

然而,事实证明你会有这样的表达:

if (VARIABLE matches "something")
[...] #This is executed when above condition is true
else (VARIABLE matches "something") #Looks very much like an elseif...
[...] #This is executed when above condition is false!
endif (VARIABLE matches "something")

结果令人困惑。我说的是我每天的经历,例如我写东西别人来问我"What does this does?"

所以,现在CMake也允许放置空括号,上面可以改写为:

if (VARIABLE matches "something")
[...] #This is executed when above condition is true
else ()
[...] #This is executed when above condition is false
endif ()

也算是比较清楚了。上面的语法还是可以用的

为了完全回答您的问题,括号也保留空参数,因为从概念上讲,CMake 中的 elseendif 是像 if 这样的宏,因此它们是用这个调用的语法,一点点(但完全不完全)作为函数。


CMake 常见问题解答中提供了基本相同的解释:Isn't the "Expression" in the "ELSE (Expression)" confusing?.

添加一点历史,在 CMake 2.4 中重复表达式是强制性的,并且仍然在 CMake 2.6,至少根据文档。该文档在 else 上含糊不清,但在 endif 上很坚定:

Note that the same expression must be given to if, and endif.

CMake 2.4.3(2006 年)已经引入了消除此约束的第一次尝试,可以通过以下方式停用它:

set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true)

此约束在 CMake 2.8

中变得完全可选

Note that the expression in the else and endif clause is optional.