Search code examples
c++g++c++20

What is the correct way to check for C++20 features on G++


My understanding was the best practice is:

#if __cplusplus >= 202002L
// code
#endif

However, it does not work, even though I do compile with -std=c++20.

Also, the output of g++ -x c++ -std=c++20 -dM -E - </dev/null | grep __cplusplus is:

#define __cplusplus 201709L

Which really confuses me, because I assumed that the correct define for C++17 is 201703L.

Am i missing something?

I have tried to check if <=> support exists. So i can also try to do:

#if __cplusplus >= __cpp_impl_three_way_comparison && __cplusplus >= __cpp_lib_three_way_comparison

However, that does not work, as both of those constants say 201907L.

P.S.

$ g++ --version
g++ (Debian 10.2.1-6) 10.2.1 20210110
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Solution

  • On version 10 and 11 of GCC stdcpp Built-in macro __cplusplus defined like this

    GCC 10:

          if (CPP_OPTION (pfile, lang) == CLK_CXX2A
          || CPP_OPTION (pfile, lang) == CLK_GNUCXX2A)
        _cpp_define_builtin (pfile, "__cplusplus 201709L");
    

    GCC 11:

          else if (CPP_OPTION (pfile, lang) == CLK_CXX20
          || CPP_OPTION (pfile, lang) == CLK_GNUCXX20)
        _cpp_define_builtin (pfile, "__cplusplus 202002L");
    

    On GCC 10.5.0 manual for C++ Standard Predefined Macros,

    Depending on the language standard selected, the value of the macro is 199711L for the 1998 C++ standard, 201103L for the 2011 C++ standard, 201402L for the 2014 C++ standard, 201703L for the 2017 C++ standard, or an unspecified value strictly larger than 201703L for the experimental languages enabled by -std=c++2a and -std=gnu++2a.

    Due to the fact that the recent version of GCC sets __cplusplus unspecified value strictly larger than 202302L for the experimental languages enabled by -std=c++26 and -std=gnu++26, that arbitrary value seems to be their working convention for experimental support.