Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 675
Marc Mutz - mmutz Avatar asked Nov 18 '20 08:11

Marc Mutz - mmutz


People also ask

What is the latest setting for STD C ++?

Select the latest version from this list. For GCC/G++, you can pass compiler flags -std=c++11, -std=c++14, -std=c++17, or -std=c++20 to enable C++11/14/17/20 support respectively. If you have GCC 8 or 9, you'll need to use -std=c++2a for C++20 support instead.

Does CMake work with C?

In the C/C++ ecosystem, the best tool for project configuration is CMake. CMake allows you to specify the build of a project, in files named CMakeLists. txt, with a simple syntax (much simpler than writing Makefiles).

Is CMake a GCC?

CMake generates files for other build systems. These can be Makefiles, Ninja files or projects files for IDEs like Visual Studio or Eclipse. The build files contain calls to compilers like GCC, Clang, or cl.exe. If you have several compilers installed, you can choose one.


Video Answer


2 Answers

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

like image 133
David Faure Avatar answered Nov 15 '22 08:11

David Faure


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.

like image 36
Denis West Avatar answered Nov 15 '22 06:11

Denis West