Home >Backend Development >C++ >How to Detect C 11 Support in Your Compiler with CMake?

How to Detect C 11 Support in Your Compiler with CMake?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 18:26:31237browse

How to Detect C  11 Support in Your Compiler with CMake?

Detecting A Compiler's C 11 Support with CMake

One of the frustrations in software development is trying to compile code that requires a feature not supported by the installed compiler. For instance, a software application requiring C 11 might not compile correctly if the user has an older compiler that only supports C 98. In such a situation, it would be helpful if the compilation could fail during the CMake run rather than at compile time.

Solution

CMake version 3.1.0 and later allows detecting what C features a C compiler supports.

<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>

In most cases, you won't have to specify the C features directly but instead specify the required C features and let CMake deduce the C standard. CMake will then ensure that the compiler is invoked with the correct flags (e.g., -std=c 11).

Explicitly Declaring Your C Standard

<code class="cmake"># Explicitly set C++ standard and required features
add_executable(prog main.cc)
set_property(TARGET prog PROPERTY CXX_STANDARD 11)
set_property(TARGET prog PROPERTY CXX_STANDARD_REQUIRED ON)</code>

Using Target Compile Features

<code class="cmake"># Specify required C++ features and let CMake deduce the C++ standard
target_compile_features(foobar PRIVATE
  cxx_strong_enums
  cxx_constexpr
  cxx_auto_type)</code>

The above is the detailed content of How to Detect C 11 Support in Your Compiler with CMake?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn