Purpose of CMake ENDIF and ELSE arguments

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.


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


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.

Tags:

Cmake