34

The Gnu C++ compiler seems to define __cplusplus to be 1

#include <iostream> 
int main() {
  std::cout << __cplusplus << std::endl;
}

This prints 1 with gcc in standard c++ mode, as well as in C++0x mode, with gcc 4.3.4, and gcc 4.7.0.

The C++11 FDIS says in "16.8 Predefined macro names [cpp.predefined]" that

The name __cplusplus is defined to the value 201103L when compiling a C++ translation unit. (Footnote: It is intended that future versions of this standard will replace the value of this macro with a greater value. Non-conforming com- pilers should use a value with at most five decimal digits.)

The old std C++03 had a similar rule.

Is the GCC deliberatly setting this to 1, because it is "non-conforming"?

By reading through that list I thought that I could use __cplusplus to check in a portable way if I have a C++11 enabled compiler. But with g++ this does not seem to work. I know about the ...EXPERIMENTAL... macro, but got curious why g++ is defining __cplusplus this way.

My original problem was switch between different null-pointer-variants. Something like this:

#if __cplusplus > 201100L
#  define MYNULL nullptr
#else
#  define MYNULL NULL
#endif

Is there a simple and reasonably portable way to implement such a switch?

towi
  • 21,587
  • 28
  • 106
  • 187
  • 13
    Side note: I haven't fully read this thread, but this was acknowledged as a bug in g++ (10 years ago!) and is fixed in 4.7.0: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=1773 – wkl Sep 23 '11 at 13:56
  • How about `#ifndef nullptr` `#define nullptr NULL` `#endif` or `#ifdef nullptr` `#define MYNULL nullptr` `#else` `#define MYNULL NULL` `#endif` – Robin Hsu Dec 22 '14 at 06:55

3 Answers3

32

This was fixed about a month ago (for gcc 4.7.0). The bug report makes for an interesting read: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=1773

Kusalananda
  • 14,885
  • 3
  • 41
  • 52
  • Whow, I updateded my svn tree last week, but had not run the test code on *that* compiler. Wait... Yes, you are correct! gcc-4.7.0 from last week: `./define-cplusplus.x 199711` – towi Sep 23 '11 at 14:08
  • 1
    The bug was open for over 10 years... Interesting read indeed. – Richard Sep 23 '14 at 20:43
1

If I recall correctly this has to do with Solaris 8 causing issues when __cplusplus is set as it should. The gcc team decided at the time to support the Solaris 8 platform rather than be compliant in this particular clause. But I noticed that the latest version of gcc ends the Solaris 8 support, and I guess this is a first step in the right direction.

wilhelmtell
  • 57,473
  • 20
  • 96
  • 131
0

It is a very old g++ bug.

That is, the compiler is not conforming.

Apparently it can't be fixed because fixing it would break something on a crazy platform.

EDIT: oh, I see from @birryree's comment that has just been fixed, in version 4.7.0. So, it was not impossible to fix after all. Heh.

Cheers & hth.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331