CraigDavid
CraigDavid

Reputation: 1246

How to error out cleanly in CMake if CMAKE_CXX_STANDARD cannot be met?

CMake provides CMAKE_CXX_STANDARD for specifying the required C++ Standard.

set (CMAKE_CXX_STANDARD 17)

However, if your compiler is old... say gcc4... it will still attempt to compile the sources, and it will of course fail with bizarre error messages, due to missing compiler features.

Is there a clean way to make CMake detect this missing support, and fail in a more obvious way?

Upvotes: 2

Views: 415

Answers (2)

Alois Klink
Alois Klink

Reputation: 856

Using target_compile_features for more control

As KamilCuk mentioned in their answer, you can check for cxx_std_17.

Additionally, you can set the requirement on a target with:

target_compile_features(my_example_library PUBLIC cxx_std_17)

Source https://cmake.org/cmake/help/latest/manual/cmake-compile-features.7.html#requiring-language-standards

This is more verbose, but it allows you to specify that only some targets need certain standards. The same syntax can also be used to require only specific features, full list found in CMAKE_CXX_KNOWN_FEATURES.

Simpler option for CMAKE_CXX_STANDARD, set CXX_STANDARD_REQUIRED

However, if you're using CMAKE_CXX_STANDARD, it's much easier to just set CMAKE_CXX_STANDARD_REQUIRED, e.g.:

# will affect any library/target defined after this
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
# also recommended, uses -std=c++17 instead of -std=gnu++17
# if you code is compatible with non-GCC compilers too
# set(CMAKE_CXX_EXTENSIONS OFF)

You'll get an error that looks something like:

CMake Error in CMakeLists.txt:
  Target "my_example_library" requires the language dialect "C17" (with
  compiler extensions).  But the current compiler "GNU" does not support
  this, or CMake does not know the flags to enable it.

Upvotes: 2

KamilCuk
KamilCuk

Reputation: 141165

From https://cmake.org/cmake/help/latest/variable/CMAKE_CXX_STANDARD.html :

See the cmake-compile-features(7) manual for information on compile features and a list of supported compilers.

From https://cmake.org/cmake/help/latest/manual/cmake-compile-features.7.html#manual:cmake-compile-features(7) :

The CMAKE_C_KNOWN_FEATURES, CMAKE_CUDA_KNOWN_FEATURES, and CMAKE_CXX_KNOWN_FEATURES global properties contain all the features known to CMake, regardless of compiler support for the feature. The CMAKE_C_COMPILE_FEATURES, CMAKE_CUDA_COMPILE_FEATURES , and CMAKE_CXX_COMPILE_FEATURES variables contain all features CMake knows are known to the compiler, regardless of language standard or compile flags needed to use them.

From https://cmake.org/cmake/help/latest/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.html#prop_gbl:CMAKE_CXX_KNOWN_FEATURES :

cxx_std_17

Compiler mode is at least C++ 17.

Check:

if ("cxx_std_17" IN_LIST CMAKE_CXX_COMPILE_FEATURES)

Upvotes: 1

Related Questions