Skip to content

Commit

Permalink
CMake: Refine mechanism for checking compiler flags
Browse files Browse the repository at this point in the history
  • Loading branch information
jppelteret committed Oct 1, 2022
1 parent 70bc2c5 commit ce33395
Showing 1 changed file with 34 additions and 10 deletions.
44 changes: 34 additions & 10 deletions cmake/setup_compiler_flags.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -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()


##
Expand Down

0 comments on commit ce33395

Please sign in to comment.