Marc Mutz - mmutz
Marc Mutz - mmutz

Reputation: 25313

How to enable `/std:c++latest` in cmake?

I can set CMAKE_CXX_STANDARD to 17 to get /std:c++17, but I can't set it to latest, can I? I guess I can just brute-force it with

if (MSVC)
    add_compiler_options(/std:c++latest)
endif()

of course, but is there an idiomatic way to get /std:c++latest, maybe even toolchain-agnostic?

EDIT Why would anybody want this? Unlike Clang and GCC, MSVC doesn't seem to define /std:c++2a to enable post-C++17 features. It simply uses /std:c++latest for that. If I'm building a code base with a set of known compilers, I know which C++20 features I can use, but I need to tell the build system to enable everything each compiler is capable of.

Upvotes: 16

Views: 17951

Answers (3)

David Faure
David Faure

Reputation: 1997

Until CMake 3.20.3, if you ask for C++20, using set(CMAKE_CXX_STANDARD 20), you'll get -std:c++latest. Proof:

  if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.12.25835)
    set(CMAKE_CXX20_STANDARD_COMPILE_OPTION "-std:c++latest")
    set(CMAKE_CXX20_EXTENSION_COMPILE_OPTION "-std:c++latest")
  endif()

(from Modules/Compiler/MSVC-CXX.cmake in the cmake sources)

UPDATE: Since CMake 3.20.4, set(CMAKE_CXX_STANDARD 20) gets you -std:c++20, so you need set(CMAKE_CXX_STANDARD 23) to get -std:c++latest -- assuming that your MSVC compiler version is 16.11 Preview 1 or later (see cmake commit 3aaf1d91bf353).

Upvotes: 30

Denis West
Denis West

Reputation: 81

Assuming you use a compiler that is already C++20 compliant and you don't want to put an "if" and an extra assignment, as was done in a previous answer, this is a standard way to put the latest version of C++ with CMake when using Visual Studio or another compiler.

target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_20)

Here is the list of features supported by CMake in the case of C++ CMAKE_CXX_KNOWN_FEATURES.

Upvotes: 4

secdet
secdet

Reputation: 308

Supported values are 98, 11, 14, 17, and 20.

According to the CMake Docs

Upvotes: -6

Related Questions