What happens if I use extern “C++” with a C toolch

2019-06-18 09:02发布

问题:

My question is mainly about the fact that a C++ toolchain "understands" both C and C++, so if I feed some code with an extern "C" to a c++ toolchain I assume it can understand what to do with that; but what if I feed code with extern "C++" to a C toolchain ?

What is the expected behaviour ?

回答1:

If the compiler ALSO understands C++, it may accept it. If it's a pure C compiler it will object (just like it will on extern "C" as that syntax is not valid C - this is why it's typically enclosed with #ifdef __cplusplus or some such)



回答2:

It is supposed to not compile, it is not valid C syntax.

The standard approach to make C declarations in a header file work both in a C and C++ compiler is to rely on a preprocessor symbol that's only defined in a C++ compiler. Like this:

#ifdef __cplusplus
extern "C" {
#endif

// C declarations here
// ...

#ifdef __cplusplus
}
#endif

Every C++ compiler defines __cplusplus.



回答3:

extern "C++" is not valid C code, so a conforming C compiler must issue a diagnostic. There is no requirement that it not compile the code. Having issued a diagnostic, the compiler is free to do whatever its implementor decided was appropriate.



回答4:

If you wrote some other compiler with such option you can do this.

As answered by @Mats we have another procedure to achieve this is #ifdef __cplusplus. Moreover what you are trying is error only.



标签: c++ c extern