-1

How do I test to see if I am linking in C++ or C using macros? Say I have code that should link as C in a C++ file, I would use extern "C"{//code here}which would make my code in a link as C . How would I set up my name.c file to work for both C and C++. Something like...

#ifdef C++//or other macro
extern "C"{
#endif

#ifdef C++
}
#endif

What is the proper macro to replace the "C++" I have above, and will it be cross platform? or how can I set it up to be cross platform?

Also, What is the significance of having to do the extern "C"{} for C code in a C++ file?

Any help is appreciated. Thanks in advance.

Alex Zywicki
  • 2,263
  • 1
  • 19
  • 34
  • 6
  • (also, if you have **two** questions, then post two separate questions. The answer to your second question is not only easily googleable [well, so is the first one], but it's quite lengthy.) – The Paramagnetic Croissant Jul 05 '14 at 15:15
  • @user3477950 I will be sure to do that next time if I have a multi part question. – Alex Zywicki Jul 05 '14 at 15:21
  • @user3477950 the answer is actually very short. *There is no such thing as C code in a C++ file*. – n. m. could be an AI Jul 05 '14 at 15:23
  • @n.m. Well, yeah, too bad a lot of people are trying to treat C as if it was a subset of C++... :'( – The Paramagnetic Croissant Jul 05 '14 at 15:24
  • @n.m. When I said "C code in a C++ file" I meant code that should be linked as C rather than C++. I will edit to clarify. – Alex Zywicki Jul 05 '14 at 15:26
  • @n.m. Yes there in theory is no such thing as C code in a C++ file but I would argue that there is such a things a "C compatible" code in a C++ file, meaning code from a .cpp file that if put into a .c file would compile and link without modification. Much like C++ being am extension of the C language allowing code written for a C compiler to function without major modification in a C++ environment just in reverse. – Alex Zywicki Jul 05 '14 at 15:41
  • Why the heck is this voted down? It's a perfectly reasonable question! – Owl Jul 19 '17 at 00:17

1 Answers1

2

"What is the proper macro to replace the "C++""

It's #ifdef __cplusplus

#ifdef __cplusplus
extern "C"{
#endif

//.....

#ifdef __cplusplus
}
#endif

For "...What is the significance of having to do....?"

Read : In C++ source, what is the effect of extern “C”?

Community
  • 1
  • 1
P0W
  • 46,614
  • 9
  • 72
  • 119