[C++再学习系列] 深入extern关键字

变量的声明与定义:

 

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

 

A declaration makes known the type and name of the variable to 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 the extern keyword. A declaration that is not also a definition consists of the object's name and its type preceded by the keyword extern.

 

函数的定义与声明很好区分,因为函数必须得有函数体编译器才能给它分配空间。而变量仅仅需要要个名字和它的类型编译器就可以分配空间给它。

因此,声明只是告诉编译器声明的变量和函数是存在的,但并没有真正分配空间给它,所以当后面的代码用到前面声明的变量或函数时,编译器在编译的时候不会报错,但是在链接的时候会报错,因为链接的时候编译器会去寻找这些变量和函数的内存地址,因为只声明了但没定义,链接器当然找不到它们了,所以就报错了。而对它们进行定义了的话编译器就会给它们分配空间,它们就有自己的地址了,这时就能链接了。

总之,定义是要分配空间的,所以定义只能有一次。而声明不分配空间,可声明多次。

 

extern 关键字

extern 可以置于变量或者函数前,以标示变量或者函数的定义在别的文件中,提示编译器遇到此变量和函数时在其他模块 (obj 文件或库文件 ) 中寻找其定义。另外, extern 也可用来进行链接指定。

并不是所有的变量都能用 extern 声明,只有全局变量并且没有被 static 声明的变量才能声明为 extern 。所以如果你不想自己源文件中全局的变量被其他文件引用,你就可以给变量加上 static 声明。

示例:

声明且定义:

int fudgeFactor;

std::string hello("Hello, world!");

void foo() {/* … */}

 

声明:

extern int fudgeFactor;

extern string hello;

void foo();         // "extern" is optional with function declarations

 

注意:使用 extern 关键字,要确保其声明的变量和函数一定要在某个 cpp 文件中定义。不要直接在 h 文件中定义,这样多次 include 后将产生多处定义。

参考: http://blog.csdn.net/zhenjing/archive/2009/07/11/4340306.aspx

 

常见用法

1)      定义跨文件的全局变量和函数。

参考: http://blog.csdn.net/zhenjing/archive/2009/07/11/4340306.aspx

2)      链接指定。示例:链接 C 库函数

// .h 文件的头上

#ifdef __cplusplus

#if __cplusplus

extern "C"{

  #endif

  #endif /* __cplusplus */

 …

 …

  //.h 文件结束的地方

  #ifdef __cplusplus

  #if __cplusplus

}

#endif

#endif /* __cplusplus */

 

同时建议参考:

全局或静态变量 ( 对象 ) 的初始化:

http://blog.csdn.net/zhenjing/archive/2009/07/31/4398465.aspx

 

跨编译单元的对象初始化:

http://blog.csdn.net/zhenjing/archive/2009/07/31/4398491.aspx

      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值