Why does CMake syntax have redundant parentheses e

2019-04-08 02:59发布

CMake's ifs go like this:

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

With else if (...) the (...) tests for a separate condition.
Why else (...) and not just else? Why endif (...) and not endif?


Cmake's functions go like this:

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

Why endfunction(funcname ...) and not simply endfunction?


I can omit the contents of the redundant parenthesis where they appear, like so: endif (). What's the purpose of this construct?

1条回答
迷人小祖宗
2楼-- · 2019-04-08 03:48

I believe the initial intention was that, by repeating at each clause (for example, else statement) the initial expression (for example, the one at the if statement) it would make more clear which statement was actually closed, and the parser could verify and warn nothing wrong was going on.

However, it turned out that you would have expression like:

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")

Which turned out to be confusing. I am speaking about my every day experience, e.g. I write something and somebody else come to ask me "What does this does?"

So, now CMake allows also to put empty parenthesis, the above can be rewritten as:

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

Which can be considered clearer. The grammar above can still be used.

To completely answer to your question, the parenthesis stay also with empty arguments because conceptually else and endif in CMake are macros like if, and therefore they are invoked with this grammar, a little bit (but not at all exactly) as functions.


Basically the same explanation is available in CMake FAQs: Isn't the "Expression" in the "ELSE (Expression)" confusing?.

To add a little bit of history, in CMake 2.4 repeating the expression was obligatory, and still in CMake 2.6, at least according to the documentation. The documentation was ambiguous on else, but adamant on endif:

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

The first try to remove this constraint was introduced already with CMake 2.4.3 (year 2006), where it was possible to deactivate it by writing:

set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true)

This constraint became fully optional with CMake 2.8

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

查看更多
登录 后发表回答