【C++ 拾遗】extern 关键字

Separate compilation

  • let us split our programs into several files, each of which can be compiled independently.

  • allows programs to be written in logical parts.

Distinction between a declaration and a definition

To support separate compilation, C++ distinguishes between declarations and definitions. A declaration makes a name known to the program. A definition creates the associated entity.

A variable declaration specifies the type and name of a variable. A variable definition is a declaration. In addition to specifying the name and type, a definition also allocates storage and may provide the variable with an initial value.

One Definition Rule

Variables must be defined exactly once but can be declared many times.

Where extern comes in

When we separate a program into multiple files, we need a way to share code across those files. For example, code written in one file may need to use a variable defined in another file. A file that wants to use a name defined elsewhere includes a declaration for that name.

To obtain a declaration that is not also a definition, we add the extern keyword and must not provide an explicit initializer:

extern int i;    // declares but does not define i;
int j; //    declares and defines j

In this case, the extern signifies the the variable i is not local to this file and that its definition will occur elsewhere.

Any declaration that includes an explicit initializer is a definition. We can provide an initializer on a variable defined as extern, but doing so overrides the extern. An extern that has an initializer is a definition.

It is an error to provide an initializer on an extern inside a function.

extern 的第二个用法

To define a single instance of a const variable, we use the keyword extern on both its definition and declaration(s). In other words, to share a const object among multiple files, you must define the variable as extern.

extern 的第三个用法

explicit instantiation a.k.a. extern template

转载于:https://www.cnblogs.com/Patt/p/10657830.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值