Even if I don't want to tie my CMakeLists file to a specific compiler, I still would like to enable certain options like -Wall that I know many compilers support.
Currently I am doing it like this to set the -Wall and -pedantic flags if they are accepted by the current compiler:
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()
Is there a better way? Or at least a nicer way to do essentially the same thing? The above is incredibly verbose and ugly for what it achieves. A much nicer command would be something like:
enable_cxx_compiler_flags_if_supported(-Wall -pedantic)
What is the proper way, in modern CMake, to choose the compiler (and to change it, on demand)? Either using a toolchain file, using cmake -DCMAKE_$ {LANG}_COMPILER= on the first configure, or CC=…
Append Compiler Flags The initial content from the cached CMAKE_CXX_FLAGS variable is a combination of CMAKE_CXX_FLAGS_INIT set by CMake itself during OS/toolchain detection and whatever is set in the CXXFLAGS environment variable. So you can initially call: cmake -E env CXXFLAGS="-Wall" cmake..
On current compilers, it is not possible to do this through build options. This is because of how the build model works: The compiler will get invoked once for every source file and all the header files included by that source file will invariably use the same build options as the source file itself. So CMake will not be able to help you here.
Append Linker Flags The linker options are more or less equivalent to the compiler options. Just that CMake's variable names depend on the target type (EXE, SHARED or MODULE).
As suggested in a comment I've tried to write a function myself. I obviously don't know much CMake, but here is my try at a function that checks both that the flag is supported using check_cxx_compiler_flag and also checks that the flag isn't already set (to avoid flooding the list with duplicates).
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With