Purpose of CMake ENDIF and ELSE arguments

2019-06-16 19:49发布

In CMake the ELSE and ENDIF control flow functions take expressions as arguments. These are optional according to the documentation. What is the purpose of these then? Is it just to make the original IF expression clearer for maintenance purposes, or does it provide some functionality?

标签: cmake
4条回答
家丑人穷心不美
2楼-- · 2019-06-16 20:23

These expressions are optional as you said and they are useful when you have nested if() statements - cmake will warn you when expr in endif() doesn't match expr in nearest if().

The same is for else().

Simply - this protects you from mistakes in if() else() endif() nested chains.

查看更多
做个烂人
3楼-- · 2019-06-16 20:23

It is not that the else and endif are optional. The expression inside () are optional. From the documentation:

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

Previous versions of cmake required that you repeat the condition in else and endif:

if(FOO)
...
else(FOO)
...
endif(FOO)
查看更多
别忘想泡老子
4楼-- · 2019-06-16 20:28

The arguments to else() and endif() were required before version 2.6.0. From the CMake FAQ:

As of CMake 2.6.0 the ELSE() and ENDIF() constructs can be empty. The same is true for closing constructs on ENDMACRO(), ENDFUNCTION(), and ENDFOREACH(). If you require 2.4.x compatibility, CMake 2.4.3 or greater recognizes the CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS option (which is superfluous in 2.6.0)

Other than helping with readability, they do not seem to have any function. See also this excellent answer.

查看更多
男人必须洒脱
5楼-- · 2019-06-16 20:30

The optional arguments makes it easier to find matching if/else/endif parts, thus it is for better readability.

I personal do not use the arguments, as I find the else statement else(condition) really confusing like in

if(condition)
   // do something
else(condition)
   // do something else
endif(condition)

I often misread else(condition) as elseif(condition).

查看更多
登录 后发表回答