7

The question title should say it all, but here's an example of what sort of thing I'm looking for:

#ifndef THE_IDENTIFIER_THAT_WOULD_INDICATE_BEING_COMPILED_AS_CPLUSPLUS

/*
 * Example of something that would matter.
 */
typedef enum _bool bool;
enum _bool { false, true };

#endif

What is the identifier? It's bugging me severely, as I know I've seen code that does this before.

I'm using GCC, by the way.

(I'm surprised I couldn't find a duplicate somewhere on SO. If someone else can find one, feel free to redirect me and close this as a dupe.)

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
William
  • 1,849
  • 2
  • 23
  • 38
  • 4
    It's `__cplusplus`. The macro is defined by C++ compilers. Duplicated from: http://stackoverflow.com/questions/3858308/using-c-preprocessor-to-determine-compilation-environment – 逆さま Nov 10 '10 at 21:27
  • 2
    btw: C99 added a native boolean type called `_Bool`, aliased to `bool` if you include `` – Christoph Nov 10 '10 at 21:49
  • See also [Preprocessor directive to test if this is C or C++](http://stackoverflow.com/questions/12548490/preprocessor-directive-to-test-if-this-is-c-or-c) to learn about `extern "C"` and some ways to handle. – Jonathan Leffler Sep 23 '12 at 06:43
  • 1
    I find it amusing that 6 answers and a comment that states the answer all hit enter at the same time: `Nov 10 '10 21:27` – Adrian Feb 01 '19 at 21:30

6 Answers6

12
#ifndef __cplusplus

If I remember correctly.

frast
  • 2,670
  • 1
  • 25
  • 34
5

The identifier is __cplusplus

#ifdef __cplusplus
#error NO C++ PLEASE
#endif
pmg
  • 103,426
  • 11
  • 122
  • 196
2

#ifdef __cplusplus

with a few really ancient compilers (early versions of cfront and a couple of ports) it was c_pluplus, IIRC.

Jerry Coffin
  • 455,417
  • 76
  • 598
  • 1,067
2
#ifdef __cplusplus
nmichaels
  • 47,648
  • 12
  • 99
  • 131
2

#ifdef __cplusplus

I think the file extension matters too, if the C++ compiler is given a .c file it will compile it as C code. i have nothing to back this up though.

James
  • 8,897
  • 2
  • 28
  • 47
1

The identifier you are looking for is __cplusplus, which can be used like this:

#ifdef __cplusplus
// Code being compiled as C++.
#endif
Richard J. Ross III
  • 54,187
  • 24
  • 128
  • 194
alecov
  • 4,603
  • 2
  • 28
  • 52