CMake 无法处理 if 中的合取

Fab*_*ian 0 cmake

我有以下最小的非工作示例 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()
Run Code Online (Sandbox Code Playgroud)

在 Windows 下使用 CMake 3.24.2 会产生以下输出(除了通常的编译器标识等,其中没有警告或错误):

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
Run Code Online (Sandbox Code Playgroud)

为什么我不允许使用像这样的变量ENABLE_COVERAGE和像这样的预定义符号的连接WIN32

Kam*_*Cuk 5

CMake 文档https://cmake.org/cmake/help/latest/command/if.html#variable-expansion对此进行了解释。

以下行为空ENABLE_COVERAGE

if(NOT WIN32 AND ${ENABLE_COVERAGE})
Run Code Online (Sandbox Code Playgroud)

扩展到:

if(NOT WIN32 AND)
Run Code Online (Sandbox Code Playgroud)

这是无效的。

根据经验,您永远不应该使用${...}inside if。请记住使用 来检查您的脚本cmake-lint

为什么我不允许将像 ENABLE_COVERAGE 这样的变量和像 WIN32 这样的预定义符号结合起来?

你是,你想要:

 if(NOT WIN32 AND ENABLE_COVERAGE)
Run Code Online (Sandbox Code Playgroud)

或者可能:

 if(NOT WIN32 AND "${ENABLE_COVERAGE}")
Run Code Online (Sandbox Code Playgroud)

取决于您想要如何处理https://cmake.org/cmake/help/latest/command/if.html#basic-expressions