The best way to port compiler options like -Wall and -pedantic in CMake

Even if I don’t want to bind my CMakeLists file to a specific compiler, I still need to include certain options, such as -Wall, which I know that many compilers support.

Currently, I am doing this to set the -Wall and -pedantic flags if 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 pretty much the same thing? The above is incredibly verbose and ugly to achieve. A nicer command would look something like this:

enable_cxx_compiler_flags_if_supported(-Wall -pedantic)
+4
source share
1 answer

, . , , 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")
+4

Source: https://habr.com/ru/post/1612312/


All Articles