Code
Here are two simple CMake functions that take a list of compiler flags, and append those that do not result in an error when used to the supplied variable.
Depending on which version of CMake you need to support, you might want to
look into the COMPILE_FLAGS
property and target_compile_options()
.
include(CheckCCompilerFlag)
function(add_c_compiler_flags var)
foreach(flag ${ARGN})
string(REGEX REPLACE "[^a-zA-Z0-9]+" "_" flag_var "CFLAG_${flag}")
check_c_compiler_flag("${flag}" ${flag_var})
if(${flag_var})
set(${var} "${${var}} ${flag}")
endif()
endforeach()
set(${var} "${${var}}" PARENT_SCOPE)
endfunction()
include(CheckCXXCompilerFlag)
function(add_cxx_compiler_flags var)
foreach(flag ${ARGN})
string(REGEX REPLACE "[^a-zA-Z0-9]+" "_" flag_var "CXXFLAG_${flag}")
check_cxx_compiler_flag("${flag}" ${flag_var})
if(${flag_var})
set(${var} "${${var}} ${flag}")
endif()
endforeach()
set(${var} "${${var}}" PARENT_SCOPE)
endfunction()
Examples
# Add a single flag
add_c_compiler_flags(CMAKE_C_FLAGS "-Wall")
# Add to the flags used for Release builds
add_c_compiler_flags(CMAKE_C_FLAGS_RELEASE "-fomit-frame-pointer")
# Add a list of flags
add_c_compiler_flags(CMAKE_C_FLAGS "-Wall;-Wextra;-pedantic")
# Add a long list of flags
add_c_compiler_flags(CMAKE_C_FLAGS
-Wall
-Wextra
-pedantic
-Wshadow
-Wpointer-arith
-Wcast-qual
-Wcast-align
-Wstrict-prototypes
-Wmissing-prototypes
)