Home > Article > Backend Development > How can CMake be Used to Automatically Detect and Configure C 11 Compatibility?
Automating C 11 Compatibility Detection in CMake
Problem:
How can CMake be utilized to automatically detect and configure C 11 compatibility in a project?
Solution:
CMake Version 3.1.0 and Above:
With CMake version 3.1.0 or later, the following code snippet enables detection of C features supported by the compiler:
<code class="cmake">cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR) project(foobar CXX) message("Your C++ compiler supports these C++ features:") foreach(i ${CMAKE_CXX_COMPILE_FEATURES}) message("${i}") endforeach()</code>
Configuring C Standards:
Instead of manual detection, CMake provides two methods to declare the C standard for compilation:
Explicit Standard Specification:
Set the target properties CXX_STANDARD and CXX_STANDARD_REQUIRED to explicitly specify the C standard:
<code class="cmake">set_property(TARGET prog PROPERTY CXX_STANDARD 11) set_property(TARGET prog PROPERTY CXX_STANDARD_REQUIRED ON)</code>
Feature-Dependent Standard Detection:
Using the target_compile_features command, specify the C features required by the project. CMake will deduce the appropriate C standard from these features:
<code class="cmake">target_compile_features(foobar PRIVATE cxx_strong_enums cxx_constexpr cxx_auto_type)</code>
Additional Functionality:
The CMake global property CMAKE_CXX_KNOWN_FEATURES provides a list of known C features. This allows for detecting the specific features supported by the compiler.
The above is the detailed content of How can CMake be Used to Automatically Detect and Configure C 11 Compatibility?. For more information, please follow other related articles on the PHP Chinese website!