[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關鍵字
????? 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后將產生多處定義。
參考:http://blog.csdn.net/zhenjing/archive/2009/07/11/4340306.aspx
?
總結
以上是生活随笔為你收集整理的[C++再学习系列] 变量的声明、定义与extern关键字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 公司的费用报销系统【为什么不好用】?做业
- 下一篇: 二、用FTP同步服务器