2009-08-18 51 views
20

可能重复:
Why do we need extern “C”{ #include <foo.h> } in C++?什么时候在C++中使用extern“C”?

我经常看到类似的编码方案:

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

为什么要使用一个extern "C"块?我们可以用C++中的某些东西替代它吗?使用extern "C"有什么好处吗?

我确实看到一个链接,解释了this,但为什么我们需要在C语言中编译一些东西?

+3

重复http://stackoverflow.com/questions/67894/why-do-we-need-extern-c-include-foo-h-in-c – Aamir 2009-08-18 06:34:09

+0

相关:http://stackoverflow.com/questions/1041866/extern-c http://stackoverflow.com/questions/717729/does-extern-c-have-any-effect-in-c http://stackoverflow.com/questions/496448/how-to-correctly次使用的最的extern-keword-在-C / – 2009-08-18 06:35:04

回答

29

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") 
    
10

一个地方的extern“C”是有道理的是,当你链接到已编译的C代码库。

extern "C" { 
    #include "c_only_header.h" 
} 

否则,你可能会因为该库包含了C-联动(_Myfunc),但C++编译器,加工库的头为C++代码的功能得到链接错误,生成的函数C++符号名称(” _myfunc @ XAZZYE“ - 这被称为mangling,对于每个编译器都是不同的)。

使用extern“C”的另一个地方是保证C连接,即使对于用C++编写的函数,例如。

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公共函数中使用函数重载。