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.
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.
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).
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With