__cplusplus < 201402L return true in gcc even when I specified -std=c++14

DMaster picture DMaster · Jun 23, 2015 · Viewed 8.5k times · Source

The directive:

#ifndef __cplusplus
  #error C++ is required
#elif __cplusplus < 201402L
  #error C++14 is required
#endif

The command-line: g++ -Wall -Wextra -std=c++14 -c -o header.o header.hpp

My g++ version: g++ (tdm-1) 4.9.2

The error C++14 is required is generated even when I added -std=c++14, I don't know why.

Please tell me how to fix this.

Answer

manlio picture manlio · Jun 23, 2015

According to the GCC CPP manual (version 4.9.2 and 5.1.0):

__cplusplus This macro is defined when the C++ compiler is in use. You can use __cplusplus to test whether a header is compiled by a C compiler or a C++ compiler. This macro is similar to __STDC_VERSION__, in that it expands to a version number. Depending on the language standard selected, the value of the macro is 199711L, as mandated by the 1998 C++ standard; 201103L, per the 2011 C++ standard; an unspecified value strictly larger than 201103L for the experimental languages enabled by -std=c++1y and -std=gnu++1y.

You can check that g++ --std=c++14 defines __cplusplus as:

 Version    __cplusplus
  4.8.3       201300L
  4.9.2       201300L
  5.1.0       201402L

For clang++ --std=c++14:

 Version    __cplusplus
  3.3          201305L
  3.4          201305L
  3.5.x        201402L
  3.6          201402L
  3.7          201402L

So a safer check should probably be:

#ifndef __cplusplus
#  error C++ is required
#elif __cplusplus <= 201103L
#  error C++14 is required
#endif

As specified in the comment, this could mean partial C++14 support.

To check for a specific feature you could also try Boost Config (especially Macros that describe C++14 features not supported).