CMake compiler feature detect
In CMake projects (or other build systems) it’s more robust to detect compiler features rather than make brittle, difficult to maintain nested if / elseif logic trees based on compiler vendor and version. There are edge cases where if() statements to work around known compiler bugs are necessary, but where we can, we use compiler feature checks instead. Each compiler vendor such as AppleClang, GNU GCC, LLVM Clang, typically publishes tables of compiler features vs. language standard support in their documentation. These tables might not cover every aspect of feature support, or the project invocation of that support may trigger bugs in specific compiler versions. Then, either hard-coded build system logic or preferably configure-time feature detection is needed.
An example using check_source_compiles in a CMake project requires C11 variable length arrays. The CMakeLists.txt would look like:
include(CheckSourceCompiles)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
# so that check_source_compiles sets the correct language standard
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
# save link time, only compile is needed
check_source_compiles(C "int main(void){
for (int i = 1; i < 5; i++){
int a[i];
}
return 0;
}"
c11vla)
if(NOT c11vla)
# fatal error or disable feature using C11 VLA
endif()
add_executable(c11demo demo.c)A similar meson.build configure-time compiler feature check example:
project('c11vla_demo', 'c',
default_options : ['c_std=c11'])
c11_vla = meson.get_compiler('c').compiles(required: true, name: 'c11_vla',
'int main(void){ for (int i = 1; i < 5; i++){ int a[i]; } return 0; }'
)