CMake C++ standard with fallback
CMake describes language standards supported by the specific C++ compiler being used by the Cmake project in CMAKE_CXX_COMPILE_FEATURES. For example, a project may with to fallback to a lower C++ standard version if the requested standard is not available. This is useful for building projects that need to support older compilers.
Use feature macros and / or CMake source code checks to define symbols within the code to fallback as necessary.
project(my LANGUAGES CXX)
set(cxx_std 17)
if("cxx_std_20" IN_LIST CMAKE_CXX_COMPILE_FEATURES)
set(cxx_std 20)
elseif(NOT "cxx_std_17" IN_LIST CMAKE_CXX_COMPILE_FEATURES)
message(WARNING "${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION} may not support at least C++17 standard")
endif()
add_executable(my_exe my.cpp)
target_compile_features(my_exe PRIVATE cxx_std_${cxx_std})
Normally the project wishes to use CMAKE_CXX_COMPILE_FEATURES instead of CMAKE_CXX_KNOWN_FEATURES, as the latter tells all the features CMake knows, rather that what the compiler knows.
The C / C++ code can use macro feature checks that detect compiler C++ / C standard support.
#if __cplusplus >= 201703L
// C++17 features
#endif
For C code likewise:
#if __STDC_VERSION__ >= 201112L
// C11 features
#endif
Related: