c++ - 何时在 C++ 中使用 extern "C"?

标签 c++ c extern-c

Possible Duplicate:
Why do we need extern “C”{ #include <foo.h> } in C++?

我经常看到这样编码的程序:

extern "C" bool doSomeWork() {
  //
  return true;
}

为什么我们使用 extern "C" block ?我们可以用 C++ 中的东西替换它吗?使用 extern "C" 有什么好处吗?

我确实看到了一个解释 this 的链接但是既然我们已经有了 C++,为什么还要用 C 编译一些东西呢?

最佳答案

extern "C"使名称不被破坏。

在以下情况下使用:

  1. 我们需要在 C++ 中使用一些 C 库

    extern "C" int foo(int);
    
  2. 我们需要将一些 C++ 代码导出到 C

    extern "C" int foo(int) { something; }
    
  3. 我们需要能够解析共享库中的符号——所以我们需要摆脱重整

    extern "C" int foo(int) { something; }
    ///
    typedef int (*foo_type)(int);
    foo_type f = (foo_type)dlsym(handle,"foo")
    

关于c++ - 何时在 C++ 中使用 extern "C"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1292138/

相关文章:

c++ - 面向对象编程和 OpenGL

c++ - 在包含自定义类型的集合中查找

c - OMP 使用 if 语句优化嵌套循环

c - 发送具有多个数字的唯一字符串客户端/服务器 TCP

c++ - 在函数定义中指定参数默认值导致错误 C2143 : syntax error : missing ')' before '='

c++ - HeapTree中的编译错误

c++ - 使用索贝尔的奇怪方向图。怎么了?

c - 用换行符在 C 中编码 Url?

c++ - extern "C"和简单的 extern 之间的区别

c++ - 指定extern “C”时,为什么Visual Studio无法给出 undefined reference 错误?