Issue
I have the following minimal non-working example as CMakeLists.txt:
project(MinimalWorkingExample)
if(NOT WIN32 AND WIN32)
message("If branch!!")
else()
message("Else branch!!")
endif()
if(${ENABLE_COVERAGE})
message("If branch 2!!")
else()
message("Else branch 2!!")
endif()
if(${ENABLE_COVERAGE} AND ${ENABLE_COVERAGE})
message("If branch 3!!")
else()
message("Else branch 3!!")
endif()
if(NOT WIN32 AND NOT WIN32)
message("If branch 4!!")
else()
message("Else branch 4!!")
endif()
if(NOT WIN32)
if(${ENABLE_COVERAGE})
message("If-If branch!!")
else()
message("If-Else branch!!")
endif()
else()
if(${ENABLE_COVERAGE})
message("Else-If branch!!")
else()
message("Else-Else branch!!")
endif()
endif()
if(NOT WIN32 AND ${ENABLE_COVERAGE})
message("Last branch")
endif()
using this with CMake 3.24.2 under windows produces the following output (besides the usual compiler identification etc., which has no warning or error in it):
Else branch!!
Else branch 2!!
Else branch 3!!
Else branch 4!!
Else-Else branch!!
CMake Error at CMakeLists.txt:36 (if):
if given arguments:
"NOT" "WIN32" "AND"
Unknown arguments specified
How come that I'm not allowed to have a conjunction of a variable like ENABLE_COVERAGE
and a predefined symbol like WIN32
?
Solution
This is explained in CMake documentation https://cmake.org/cmake/help/latest/command/if.html#variable-expansion .
The following line with empty ENABLE_COVERAGE
:
if(NOT WIN32 AND ${ENABLE_COVERAGE})
Expands to:
if(NOT WIN32 AND)
which is invalid.
As a rule of thumb, you should never use ${...}
inside if
. Remember to check your scripts with cmake-lint
.
How come that I'm not allowed to have a conjunction of a variable like ENABLE_COVERAGE and a predefined symbol like WIN32?
You are, you want:
if(NOT WIN32 AND ENABLE_COVERAGE)
Or potentially:
if(NOT WIN32 AND "${ENABLE_COVERAGE}")
Depending on how you want to handle https://cmake.org/cmake/help/latest/command/if.html#basic-expressions .
Answered By - KamilCuk Answer Checked By - Marilyn (WPSolving Volunteer)