11

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,753
  • 72
  • 57
  • 129
William
  • 1,993
  • 2
  • 23
  • 40
  • 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 – wkl 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

13
#ifndef __cplusplus

If I remember correctly.

frast
  • 2,700
  • 1
  • 25
  • 34
7

The identifier is __cplusplus

#ifdef __cplusplus
#error NO C++ PLEASE
#endif
pmg
  • 106,608
  • 13
  • 126
  • 198
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
  • 476,176
  • 80
  • 629
  • 1,111
2
#ifdef __cplusplus
nmichaels
  • 49,466
  • 12
  • 107
  • 135
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
  • 9,064
  • 3
  • 31
  • 49
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
  • 55,009
  • 24
  • 135
  • 201
alecov
  • 4,882
  • 2
  • 29
  • 55