CMake的if
s是这样的:
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")
结果令人困惑。我说的是我每天的经历,例如我写了一些东西,其他人来问我“这是做什么的?”
所以,现在CMake也允许放空括号,上面的内容可以改写为:
if (VARIABLE matches "something")
[...] #This is executed when above condition is true
else ()
[...] #This is executed when above condition is false
endif ()
这可以被认为更清楚。上面的语法仍然可以使用。
为了完全回答你的问题,括号也保持空参数,因为概念上CMake中的else
和endif
是像if
这样的宏,因此它们被这个语法调用,有点(但根本不完全)作为函数。
为了增加一点历史,在CMake 2.4重复表达是必须的,至少仍然在CMake 2.6,至少根据文档。关于else
的文档含糊不清,但坚持endif
:
请注意,必须为if和endif赋予相同的表达式。
第一次尝试删除此约束已经在CMake 2.4.3(2006年)中引入,可以通过以下方式将其停用:
set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true)
使用CMake 2.8,此约束完全可选
请注意,else和endif子句中的表达式是可选的。