在CMake中可移植地设置编译器选项(如-Wall和-pedantic)的最佳方法

Qua*_*dom 5 c++ cmake

即使我不想将我的CMakeLists文件绑定到特定的编译器,我仍然希望启用某些选项,例如-Wall,我知道许多编译器支持.

目前我这样做是为了设置-Wall和-pedantic标志,如果它们被当前编译器接受:

include(CheckCXXCompilerFlag)

check_cxx_compiler_flag(-Wall temp)
if(temp)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
endif()
check_cxx_compiler_flag(-pedantic temp)
if(temp)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic")
endif()
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?或者至少有一种更好的方式来做同样的事情?以上是令人难以置信的冗长和丑陋的成就.一个更好的命令将是这样的:

enable_cxx_compiler_flags_if_supported(-Wall -pedantic)
Run Code Online (Sandbox Code Playgroud)

Qua*_*dom 7

正如评论中所建议的,我试图自己编写一个函数.我显然不太了解CMake,但这是我尝试使用check_cxx_compiler_flag同时检查该标志是否支持的函数,并检查该标志是否已设置(以避免使重复项溢出列表).

include(CheckCXXCompilerFlag)

function(enable_cxx_compiler_flag_if_supported flag)
    string(FIND "${CMAKE_CXX_FLAGS}" "${flag}" flag_already_set)
    if(flag_already_set EQUAL -1)
        check_cxx_compiler_flag("${flag}" flag_supported)
        if(flag_supported)
            set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}" PARENT_SCOPE)
        endif()
        unset(flag_supported CACHE)
    endif()
endfunction()

# example usage
enable_cxx_compiler_flag_if_supported("-Wall")
enable_cxx_compiler_flag_if_supported("-Wextra")
enable_cxx_compiler_flag_if_supported("-pedantic")
Run Code Online (Sandbox Code Playgroud)