2009-08-18 66 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公共函數中使用函數重載。