Pedro Lopes
Pedro Lopes

Reputation: 45

CMake set project to C++ 20

I am trying to change the C++ Standard from version 17 to 20 so I can use the jthread lib.

On my root CMakelists.txt of the project I added :

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED YES)

But when I build the project again and check which version the program is running, it is still the C++ 17 version and not C++ 20.

I check the version running the following lines :

if (__cplusplus == 201703L)
    std::cout << "C++17\n";
else if (__cplusplus == 201402L)
    std::cout << "C++14\n";
else if (__cplusplus == 201103L)
    std::cout << "C++11\n";
else if (__cplusplus == 199711L)
    std::cout << "C++98\n";
else if (__cplusplus == 202002L)
    std::cout << "C++20\n";

else
    std::cout << "pre-standard C++\n";

I am using the g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0, which from what I read it supports c++ 20,g++_C++20

Does anyone has any idea of why this is happening ?

Upvotes: 2

Views: 4562

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36469

__cplusplus reports the version of the standard but its definition isn't entirely clear. GCC seems to only define it to 202002 from GCC 11 when presumably the implementation reached some arbitrary level of completion.

It is instead better to test for the existence of the specific feature you want to use using the feature test macros for example to check for std::jthread support:

#include <thread>

#ifndef __cpp_lib_jthread
#error this code requires std::jthread
#endif

Note that std::jthread is only available with libstdc++ 10: https://godbolt.org/z/eqP4j4eq1

Upvotes: 2

Related Questions