[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

原文地址:https://www.cnblogs.com/zhenjing/p/1848691.html