From ce33395a4a70db801467fbdfc6ef81734b98695a Mon Sep 17 00:00:00 2001 From: Jean-Paul Pelteret Date: Sat, 1 Oct 2022 21:36:52 +0200 Subject: [PATCH] CMake: Refine mechanism for checking compiler flags --- cmake/setup_compiler_flags.cmake | 44 ++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/cmake/setup_compiler_flags.cmake b/cmake/setup_compiler_flags.cmake index 4fe1d3ef..eb3e568c 100644 --- a/cmake/setup_compiler_flags.cmake +++ b/cmake/setup_compiler_flags.cmake @@ -17,20 +17,44 @@ # CMake macros that are used to add compiler flags # # Source: https://stackoverflow.com/a/33266748 +# https://stackoverflow.com/q/45248393 ## 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) - MESSAGE(STATUS "Compiler flag check: ${flag}") - 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) +# function(enable_cxx_compiler_flag_if_supported flag) +# string(FIND "${CMAKE_CXX_FLAGS}" "${flag}" flag_already_set) +# if(flag_already_set EQUAL -1) +# MESSAGE(STATUS "Compiler flag check: ${flag}") +# 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() + +MACRO(enable_cxx_compiler_flag_if_supported flag) + # We cannot check for -Wno-foo as this won't throw a warning so we must check for the -Wfoo option directly + # http://stackoverflow.com/questions/38785168/cc1plus-unrecognized-command-line-option-warning-on-any-other-warning + STRING(REGEX REPLACE "^-Wno-" "-W" checkedFlag ${flag}) + + SET(VarName ${checkedFlag}) + STRING(REPLACE "+" "X" VarName ${VarName}) + STRING(REGEX REPLACE "[-=]" "_" VarName ${VarName}) + + # Avoid double checks. A compiler will not magically support a flag it did not before + if(NOT ${VarName}_CHECKED) + CHECK_CXX_COMPILER_FLAG(${checkedFlag} CXX_FLAG_${VarName}_SUPPORTED) + set(${VarName}_CHECKED YES CACHE INTERNAL "") endif() -endfunction() + + IF (CXX_FLAG_${VarName}_SUPPORTED) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}" PARENT_SCOPE) + ENDIF () + + unset(VarName) + unset(checkedFlag) +ENDMACRO() ##