[英]What's the advantage of adding “extern C” in my header files?
I was reading the Section 32: How to mix C and C++ of the C++ FAQ Lite. 我正在阅读第32节:如何混合 C ++ FAQ Lite的C和C ++ 。 It says that I should strongly consider adding
extern "C" {...}
in my header file (adding the appropriate preprocessor directives, of course . That way, I can include the header "without any extern "C" nonsense" in the C++ source file: 它说我应该强烈考虑在我的头文件中添加
extern "C" {...}
(当然,添加适当的预处理器指令 。这样,我可以包含标题“没有任何extern”C“废话” C ++源文件:
// Get declaration for f(int i, char c, float x) #include "my-C-code.h"
The "nonsense", not-that-easier alternative seems to be this: “胡说八道”,不是那么容易的选择似乎是这样的:
extern "C" { // Get declaration for f(int i, char c, float x) #include "my-C-code.h" }
Why is the first option preferred? 为什么选择第一个选项? Is it just a matter of style (and the number of chars to type when someone is including them)?
这只是一个风格问题(当有人包括它们时,键入的字符数量)?
Yes, it's just a style thing. 是的,这只是一种风格。 But it does make people's lives easier when using your library, so it's probably worth sticking to.
但它确实使人们在使用你的图书馆时的生活更加轻松,所以它可能值得坚持。
Either you can put the statement once in your header file, or everyone who uses it can put the statement everywhere they include the header file. 您可以将语句一次放入头文件中,或者使用它的每个人都可以将语句放在包含头文件的任何位置。 The former certainly seems like better style to me.
前者对我来说肯定是更好的风格。
What this accomplishes is that it allows you to use that C header file with your C++ code, because the macro "__cplusplus"
will be defined. 这实现了它允许您将C头文件与C ++代码一起使用,因为将定义宏
"__cplusplus"
。 But you can also still use it with your legacy C code, where the macro is NOT defined, so it won't see the uniquely C++ construct. 但是您仍然可以将它与未定义宏的遗留C代码一起使用,因此它不会看到唯一的C ++构造。
#ifdef __cplusplus
extern "C" {
#endif
// all of your legacy C code here
#ifdef __cplusplus
}
#endif
The alternative is to put it with the #include
, but if you do it in the C header file then you only need to do it once, plus it's backwards compatible. 另一种方法是将它与
#include
,但如果你在C头文件中执行它,那么你只需要执行一次,再加上它向后兼容。
It's a pain for people trying to use your library if you don't include it. 如果您不使用图书馆,那么尝试使用图书馆的人会感到很痛苦。 If a C header is used from a C++ application without that the user will get compiler or linker errors, which can be particularly confusing for people not familiar with the problem.
如果在没有C ++应用程序的情况下使用C头,则用户将收到编译器或链接器错误,这对于不熟悉该问题的人来说尤其令人困惑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.