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

天大地大妈咪最大 提交于 2019-12-14 00:56:07

问题


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.



来源:https://stackoverflow.com/questions/18288790/what-happens-if-i-use-extern-c-with-a-c-toolchain

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!