我经常看到编写程序的方式如下:
extern "C" bool doSomeWork() {
//
return true;
}
为什么要使用extern "C"
块?我们能否在C++中用其他东西替代它?使用extern "C"
有什么好处吗?
我看到了一个解释链接,但是既然我们已经有了C++,为什么还需要编译C的内容?
我经常看到编写程序的方式如下:
extern "C" bool doSomeWork() {
//
return true;
}
为什么要使用extern "C"
块?我们能否在C++中用其他东西替代它?使用extern "C"
有什么好处吗?
我看到了一个解释链接,但是既然我们已经有了C++,为什么还需要编译C的内容?
extern "C"可以避免名称的混淆。
它被用于以下情况:
我们需要在C++中使用一些C库
extern "C" int foo(int);
我们需要将一些C++代码导出为C
extern "C" int foo(int) { something; }
我们需要解析共享库中的符号——因此我们需要消除名称修饰。extern "C" int foo(int) { something; }
///
typedef int (*foo_type)(int);
foo_type f = (foo_type)dlsym(handle,"foo")
使用 extern "C" 的一个适当场景是,当你需要链接到一个被编译为 C 代码的库时。
extern "C" {
#include "c_only_header.h"
}
否则,可能会出现链接器错误,因为库中包含具有C链接的函数(_myfunc),但是C++编译器将库的头文件处理为C++代码,并为这些函数生成了C++符号名称("_myfunc@XAZZYE" - 这称为名称修饰,对于每个编译器都不同)。extern "C" void __stdcall PrintHello() {
cout << "Hello World" << endl;
}
这样的函数可以被导出到DLL中,然后可以从其他编程语言中调用,因为编译器不会篡改它的名称。如果您添加了同名的另一个重载函数,例如:
extern "C" void __stdcall PrintHello() {
cout << "Hello World" << endl;
}
extern "C" void __stdcall PrintHello(const char *name) {
cout << "Hello, " << name << endl;
}
大多数编译器都会捕获这种情况,从而防止你在DLL公共函数中使用函数重载。