天天看點

[C++再學習系列] 變量的聲明、定義與extern關鍵字

      A definition of a variable allocates storage for thevariable and may also specify an initial value for the variable. There must be one and only one definition of a variable in aprogram.

      A declaration makes known the type and name of the variableto the program. A definition is also a declaration:When we define a variable, we declare its name and type. We can declare a name without defining it by using theextern keyword. A declaration that is not also a definition consists ofthe object's name and its type preceded by the keyword extern.

      函數的定義與聲明很好區分,因為函數必須有函數體,編譯器才給它配置設定空間。而變量僅需一個名字和類型,編譯器即可配置設定空間給它。

      聲明隻是告訴編譯器某個變量和函數是存在的,但并沒有真正配置設定空間。是以當後面的代碼用到前面聲明的變量或函數時,編譯時不會報錯,而連結時會報錯。因為連結時編譯器将尋找這些變量和函數的記憶體位址,如隻聲明未定義,連結器是找不到記憶體位址的,将報錯。總之,定義将配置設定空間,是以定義隻能有一次(多次定義則編譯錯誤)。而聲明不配置設定空間,故可聲明多次。

      extern可置于變量或者函數前,以标示變量或者函數的定義存在于其他檔案中,提示編譯器遇到此變量和函數時到其他子產品(obj檔案或庫檔案)尋找其定義。另外,extern也可用來進行連結指定。

      并非所有的變量都能用extern聲明,隻有全局變量并且沒有被static聲明的變量才能聲明為extern。如果不想自己源檔案中全局的變量被其他檔案引用,加上static聲明即可。

示例:

聲明且定義:

intfudgeFactor;

std::stringhello("Hello, world!");

void foo() {/*… */}

聲明:

extern intfudgeFactor;

extern stringhello;

voidfoo();         // "extern" isoptional with function declarations

注意:使用extern關鍵字,要確定其聲明的變量和函數一定要在某個cpp檔案中定義。不要直接在h檔案中定義,這樣多次include後将産生多處定義。

本文轉自 zhenjing 部落格園部落格,原文連結:http://www.cnblogs.com/zhenjing/archive/2010/10/12/1848691.html   ,如需轉載請自行聯系原作者

繼續閱讀