extern的用法 点击:129 | 回复:0



研讨会宣传员_3259

    
  • [版主]
  • 精华:3帖
  • 求助:110帖
  • 帖子:1927帖 | 14403回
  • 年度积分:102
  • 历史总积分:64749
  • 注册:2020年3月27日
发表于:2016-10-18 14:38:27
楼主

声明用于向程序表明变量的类型和名字。定义也是声明:当定义变量时我们声明了它的类型和名字。可以通过使用extern关键字声明变量名而不定义它。不定义变量的声明包括对象名、对象类型和对象类型前的关键字extern:

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



An extern declaration is not a definition and does not allocate storage. In effect, it claims that a definition of the variable exists elsewhere in the program. A variable can be declared multiple times in a program, but it must be defined only once.

extern 声明不是定义,也不分配存储空间。事实上,它只是说明变量定义在程序的其他地方。程序中变量可以声明多次,但只能定义一次。

A declaration may have an initializer only if it is also a definition because only a definition allocates storage. The initializer must have storage to initialize. If an initializer is present, the declaration is treated as a definition even if the declaration is labeled extern:

只有当声明也是定义时,声明才可以有初始化式,因为只有定义才分配存储空间。初始化式必须要有存储空间来进行初始化。如果声明有初始化式,那么它可被当作是定义,即使声明标记为 extern:

extern double pi = 3.1416; // definition

Despite the use of extern, this statement defines pi. Storage is allocated and initialized. An extern declaration may include an initializer only if it appears outside a function.

虽然使用了 extern ,但是这条语句还是定义了 pi,分配并初始化了存储空间。只有当 extern 声明位于函数外部时,才可以含有初始化式。

Because an extern that is initialized is treated as a definition, any subseqent definition of that variable is an error:

因为已初始化的 extern 声明被当作是定义,所以该变量任何随后的定义都是错误的:

extern double pi = 3.1416; // definition
double pi; // error: redefinition of pi

Similarly, a subsequent extern declaration that has an initializer is also an error:

同样,随后的含有初始化式的 extern 声明也是错误的:

extern double pi = 3.1416; // definition
extern double pi; // ok: declaration not definition
extern double pi = 3.1416; // error: redefinition of pi

The distinction between a declaration and a definition may seem pedantic but in fact is quite important.

声明和定义之间的区别可能看起来微不足道,但事实上却是举足轻重的。

In C++ a variable must be defined exactly once and must be defined or declared before it is used.

在 C++ 语言中,变量必须且仅能定义一次,而且在使用变量之前必须定义或声明变量。



楼主最近还看过


热门招聘
相关主题

官方公众号

智造工程师