c++中的extern

來源:互聯網
上載者:User
用例子給你示範 
// 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的函數!
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.