When building modern C or C++ projects, it's common to want to use the latest compiler features and optimizations. But not all compilers - or even versions of the same compiler - support the same options. If you add unsupported options, you'll end up with compiler errors and potentially broken builds on different platforms. Fortunately, CMake makes it possible to detect and apply compiler options conditionally, only if the compiler supports them. This ensures the builds stay portable across environments. This tutorial explains how to set compiler options only if supported using CMake.
The provided CMake script defines a custom function that checks whether each provided compiler option (flag) is supported for a given language (e.g. C
or CXX
). If an option is supported, it conditionally adds it to the target's compile options using generator expressions, ensuring the option is applied only when compiling in the specified language. This makes the build more portable and prevents errors caused by unsupported options on different compilers.
cmake_minimum_required(VERSION 3.27)
project(myapp C CXX)
set(CMAKE_CXX_STANDARD 17)
add_executable(${PROJECT_NAME} main.cpp lib.c)
function(target_supported_compile_options target language)
foreach (FLAG IN LISTS ARGN)
set(SUPPORTED_FLAG "SUPPORTED_${language}${FLAG}")
include(CheckCompilerFlag)
check_compiler_flag(${language} ${FLAG} ${SUPPORTED_FLAG})
if (${SUPPORTED_FLAG})
target_compile_options(${target} PRIVATE "$<$<COMPILE_LANGUAGE:${language}>:${FLAG}>")
endif ()
endforeach ()
endfunction()
target_supported_compile_options(${PROJECT_NAME} C -Wstrict-prototypes -mavx2 -mavx10.2)
target_supported_compile_options(${PROJECT_NAME} CXX -Wnon-virtual-dtor -mavx2 -mavx10.2)
Leave a Comment
Cancel reply