我在一个cpp文件中看到external "C" {...}
括起来了几个函数的定义。
根据https://isocpp.org/wiki/faq/mixing-c-and-cpp,我猜测在cpp文件中使用extern "C"
的目的是让这些被包含的C++函数可以在C程序中使用。
该链接中的示例表明,extern "C"
仅用于封装C++函数的声明,而非其定义。
只需在C++代码中声明C++函数为 extern "C",然后从C或C++代码中调用它。例如:
// C++ code: extern "C" void f(int); void f(int i) { // ... }
我在开头提到的 cpp 文件看起来是这样的:
// C++ code: extern "C" { void f(int i) { // ... } void g(int i) { // ... } }
在C++函数的声明或定义中,是否应该使用
extern "C"
? 如果是,为什么?