编译器标志在 CMake 中检查了两次 CHECK_CXX_COMPILER_FLAG

Compiler flag checked twice in CMake CHECK_CXX_COMPILER_FLAG

我使用自定义宏来检查并向 CMAKE 中的编译添加编译器标志。我为此使用的代码是:

MACRO(CheckAndAddFlag flag)
    # We cannot check for -Wno-foo as this won't throw a warning so we must check for the -Wfoo option directly
    # 
    STRING(REGEX REPLACE "^-Wno-" "-W" checkedFlag ${flag})
    SET(VarName ${checkedFlag})
    STRING(REPLACE "+" "X" VarName ${VarName})
    STRING(REPLACE "-" "_" VarName ${VarName})
    # Avoid double checks. A compiler will not magically support a flag it did not before
    MESSAGE(STATUS "Checking CXX_FLAG_${VarName}_SUPPORTED. Checked? ${VarName}_CHECKED= ${${VarName}_CHECKED} end")
    if(NOT ${VarName}_CHECKED)
        CHECK_CXX_COMPILER_FLAG(${checkedFlag} CXX_FLAG_${VarName}_SUPPORTED)
        CHECK_C_COMPILER_FLAG(${checkedFlag} C_FLAG_${VarName}_SUPPORTED)
        set(${VarName}_CHECKED YES CACHE INTERNAL "")
        MESSAGE(STATUS "Checked CXX_FLAG_${VarName}_SUPPORTED. Checked? ${VarName}_CHECKED= ${${VarName}_CHECKED} end")
    endif()
    IF (CXX_FLAG_${VarName}_SUPPORTED)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}")
    ENDIF ()
    IF (C_FLAG_${VarName}_SUPPORTED)
        set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}")
    ENDIF ()
    unset(VarName)
    unset(checkedFlag)
ENDMACRO()

我称它为与:

CheckAndAddFlag("-Wno-error=type-limits")
CheckAndAddFlag("-Wfloat-conversion")

通常它应该只检查每个标志一次,设置它的变量,然后 运行s 的 CMake 应该找到它并且不要再次检查它(try_compile 使用 MSVC 非常慢)
它适用于大多数标志,但不适用于 -Wno-error=type-limits。此处根据输出对标志进行双重检查。因此我添加了 _CHECKED 变量来解决这个问题,但即使这样也不起作用。它会再次被检查。

一些输出:

Checking CXX_FLAG__Werror=type_limits_SUPPORTED. Checked? _Werror=type_limits_CHECKED=  end
Performing Test CXX_FLAG__Werror=type_limits_SUPPORTED
Performing Test CXX_FLAG__Werror=type_limits_SUPPORTED - Failed
Performing Test C_FLAG__Werror=type_limits_SUPPORTED
Performing Test C_FLAG__Werror=type_limits_SUPPORTED - Failed
Checked CXX_FLAG__Werror=type_limits_SUPPORTED. Checked? _Werror=type_limits_CHECKED= YES end
Checking CXX_FLAG__Wfloat_conversion_SUPPORTED. Checked? _Wfloat_conversion_CHECKED= YES end
Checking CXX_FLAG__Wlong_long_SUPPORTED. Checked? _Wlong_long_CHECKED= YES end

知道为什么会这样吗?为什么变量得到设置但在下一个 CMAKE 运行 中未设置,为什么只有这个?

您将 CMake 与您的 = 登录变量名称混淆了吗?

试试这个:

STRING(REGEX REPLACE "[-=]" "_" VarName ${VarName})