何时使用 extern“C”在 C++ 中?
我经常看到这样编码的程序:
extern "C" bool doSomeWork() {
//
return true;
}
为什么我们使用 extern "C"
块?我们可以用 C++ 中的东西替换它吗?使用 extern "C"
有什么优势吗?
我确实看到了一个解释 this 的链接,但是为什么我们需要在 C 中编译一些东西我们已经有 C++ 了吗?
Possible Duplicate:
Why do we need extern “C”{ #include <foo.h> } in C++?
I have often seen programs coded like:
extern "C" bool doSomeWork() {
//
return true;
}
Why do we use an extern "C"
block? Can we replace this with something in C++? Is there any advantage to using extern "C"
?
I do see a link explaining this but why do we need to compile something in C when we already have C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
extern "C" 使名称不会被破坏。
它在以下情况下使用:
我们需要在 C++ 中使用一些 C 库
我们需要将一些 C++ 代码导出到 C
我们需要能够解析共享库中的符号 - 因此我们需要摆脱损坏
extern "C" makes names not mangled.
It used when:
We need to use some C library in C++
We need export some C++ code to C
We need an ability to resolve symbol in shared library -- so we need to get rid mangling
extern "C" 有意义的地方是当您链接到编译为 C 代码的库时。
否则,您可能会收到链接器错误,因为库包含具有 C 链接 (_myfunc) 的函数,但 C++ 编译器将库的标头处理为 C++ 代码,为函数生成了 C++ 符号名称(“_myfunc@XAZZYE” - 这是称为重整,并且每个编译器都不同)。
使用 extern "C" 的另一个地方是保证 C 链接,即使对于用 C++ 编写的函数也是如此,例如:
这样的函数可以导出到 DLL,然后可以从其他编程语言调用,因为编译不会破坏其名称。如果您添加了同一函数的另一个重载,例如。
大多数编译器都会捕获此问题,从而阻止您在 DLL 公共函数中使用函数重载。
One place where extern "C" makes sense is when you're linking to a library that was compiled as C code.
Otherwise, you might get linker errors because the library contains the functions with C-linkage (_myfunc) but the C++ compiler, which processed the library's header as C++ code, generated C++ symbol names for the functions ("_myfunc@XAZZYE" - this is called mangling and different for each compiler).
Another place where extern "C" is used is to guarantee C linkage even for functions written in C++, eg.
Such a function can be exported to a DLL and will then be callable from other programming language because the compile will not mangle its name. If you added another overload of the same function, eg.
Most compilers would then catch this and thus prevent you from using function overloads in your DLL-public functions.