为什么我们需要extern“C”{#include< foo.h> }在C ++? [英] Why do we need extern "C"{ #include <foo.h> } in C++?
问题描述
为什么我们需要使用:
externC{
#include< foo.h> ;
}
具体来说:
-
我们应该何时使用它?
-
如何在编译/链接方面如何解决需要我们使用它的问题?
<级别要求我们使用它吗?
C和C ++在表面上类似,但每个都编译成一组非常不同的代码。当您使用C ++编译器包含头文件时,编译器需要C ++代码。然而,如果它是一个C头,那么编译器期望包含在头文件中的数据被编译为某种格式--C ++'ABI'或'应用程序二进制接口',因此链接器阻塞。这是比传递C ++数据到期望C数据的函数更好的。
(为了进入真正的细节,C ++的ABI通常 /方法,因此调用 printf()
而不将原型标记为C函数,C ++实际上将生成调用 _Zprintf
所以:use externC{...};
当包括ac标题时,就是这么简单。否则,编译后的代码会出现不匹配,链接器会阻塞。然而,对于大多数头文件,你甚至不需要 extern
,因为大多数系统C头文件已经说明它们可能被C ++代码包含并已经 extern
他们的代码。
Why do we need to use:
extern "C" {
#include <foo.h>
}
Specifically:
When should we use it?
What is happening at the compiler/linker level that requires us to use it?
How in terms of compilation/linking does this solve the problems which require us to use it?
C and C++ are superficially similar, but each compiles into a very different set of code. When you include a header file with a C++ compiler, the compiler is expecting C++ code. If, however, it is a C header, then the compiler expects the data contained in the header file to be compiled to a certain format—the C++ 'ABI', or 'Application Binary Interface', so the linker chokes up. This is preferable to passing C++ data to a function expecting C data.
(To get into the really nitty-gritty, C++'s ABI generally 'mangles' the names of their functions/methods, so calling printf()
without flagging the prototype as a C function, the C++ will actually generate code calling _Zprintf
, plus extra crap at the end.)
So: use extern "C" {...};
when including a c header—it's that simple. Otherwise, you'll have a mismatch in compiled code, and the linker will choke. For most headers, however, you won't even need the extern
because most system C headers will already account for the fact that they might be included by C++ code and already extern
their code.
这篇关于为什么我们需要extern“C”{#include< foo.h> }在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!