在CMake中可移植设置编译器选项的最佳方式,如-Wall和-pedantic
问题描述:
即使我不想将我的CMakeLists文件绑定到特定的编译器,我仍然希望启用某些选项,例如-Wall,我知道很多编译器支持。在CMake中可移植设置编译器选项的最佳方式,如-Wall和-pedantic
目前,我做这样的设置-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()
有没有更好的办法?或者至少有一个更好的方法来做基本相同的事情?上述内容对于其实现的内容而言非常冗长和难看。一个更好的命令会是这样的:
enable_cxx_compiler_flags_if_supported(-Wall -pedantic)
答
正如在评论中建议我试图写一个函数我自己。我明显不知道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")
也许你可以使用['CMAKE_CXX_COMPILER_ID'(https://cmake.org/Wiki/CMake_Useful_Variables#Compilers_and_Tools)变量设置标志的每个编译器列表。 (不知道这是否是一个“更好”的方法)。否则,您可以定义一个宏或一个函数,它接受所需标志的列表并将'check_cxx_compiler_flag()'应用于它们。 – 865719
自己写入函数'enable_cxx_compiler_flags_if_supported'。也许你想添加-Werror(测试之后)。一些编译器会警告他们不理解的标志,并且会使用一系列忽略的标志来混乱编译器输出。 – usr1234567