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?
问题:
回答1:
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.
回答2:
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.
回答3:
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)
.
回答4:
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)