用例子給你示範
// 1.cpp
int x = 10;
// 2.cpp 注意沒有包含1.cpp
#include <iostream>
using namespace std;
extern int x;
int main ()
{ cout << x << endl; }
//則輸出10
兩個檔案同在一個項目(project)中,你不包含某個檔案(cpp)而可以用它內部定義的變數,(裡是.pp不是.h, 因為在.h中定義的資料不能在.cpp中用除非這個.cpp包含這個.h檔案)
例:
// 1.h
#include <iostream>
void print()
{
std::cout << "hello!" << std::endl;
}
// 2.cpp
#include <iostream>
using namespace std;
// 以上兩句在這個例子中可以不要
extern void print();
int main ()
{
print();
}
就會出錯因為1.h中的void print();在不包含它的檔案中是不可調用的,即使在聲明了extern 也於事無補,如果你將這個例子中的1.h名字換成1.cpp就對了!
從這些可以看出來,extern在這裡起的作用是告訴編譯器,你這個print()已經在某個.cpp中已經定義了,這裡只不過是聲明一下有這個東西,然後拿來用一下。定義只能出現一次,聲明卻可出現多次,也就是說extern聲明可在多個檔案中用(包括.h)
還有,你還可以屏蔽extern聲明,如第二個例子中的第二個.cpp檔案可以改成
#include <iostream>
using namespace std;
// 這裡以上兩句不能省略,因為,這裡extern void print();函數已經不起作用了,在這裡調用的而是本檔案中定義的void print()函數,其中用到了cout,endl;他們來源於std::<iostream>
extern void print();
void print()
{
cout << "world!" << endl;
}
int main ()
{
print();
}
// 輸出結果為world!
還有一個extern "C"就不用說了,用這個可以允許C++程式中調用C的函數!