如何与声明一起定义外部变量? [英] How to define extern variable along with declaration?
问题描述
维基说:
的
的extern
关键词的意思是没有确定申报。换言之,这是显式声明的变量,或强制的声明没有定义的一种方法。的另外,也可以明确地定义一个变量,即,迫使一个定义。它被分配一个初始值给一个变量完成。
块引用>该初始化变量这意味着,的的
的extern
声明作为该变量的定义。因此,/ *只是用于测试目的只* /
#包括LT&;&stdio.h中GT;
EXTERN INT Y = 0;
诠释主(){
的printf(%d个\\ N,Y);
返回0;
}应该是有效的(在C ++ 11 编译)。但与选项编译
-Wall -pedantic -Wextra -std = C99
在GCC 4.7.2,产生一个警告:【警告】'y'的初始化,并宣布的extern[默认启用]
这不应该。据我所知,
的extern INT Y = 0;
是有效相同
INT I = 0;
这是怎么回事错在这里?
解决方案标准的三个版本 - ISO / IEC 9899:1990,ISO / IEC 9899:1999和ISO / IEC 9899:2011 - 包含在一个例子同题部分的外部对象定义(C90的§6.7.2和C99和C11的§6.9.2)表示:
例1
INT I1 = 1; //定义,外部链接
静态INT I2 = 2; //定义,内部链接
EXTERN INT I3 = 3; //定义,外部链接
INT I4; //暂定定义,外部链接
静态INT I5; //暂定定义,内部链接
块引用>这个例子继续,但
的extern INT I3 = 3;
行清楚地表明,该标准表明它应该被允许。但是请注意,在标准的例子是技术上不规范(见标准的前言);他们是不是是什么,是不允许一个明确的说法。这是说,大部分人大部分时间不使用
的extern
和初始化。Wiki says:
The
extern
keyword means "declare without defining". In other words, it is a way to explicitly declare a variable, or to force a declaration without a definition. It is also possible to explicitly define a variable, i.e. to force a definition. It is done by assigning an initialization value to a variable.That means, an
extern
declaration that initializes the variable serves as a definition for that variable. So,/* Just for testing purpose only */ #include <stdio.h> extern int y = 0; int main(){ printf("%d\n", y); return 0; }
should be valid (compiled in C++11). But when compiled with options
-Wall -Wextra -pedantic -std=c99
in GCC 4.7.2, produces a warning:[Warning] 'y' initialized and declared 'extern' [enabled by default]
which should not. AFAIK,
extern int y = 0;
is effectively the same as
int i = 0;
What's going wrong here ?
解决方案All three versions of the standard — ISO/IEC 9899:1990, ISO/IEC 9899:1999 and ISO/IEC 9899:2011 — contain an example in the section with the title External object definitions (§6.7.2 of C90, and §6.9.2 of C99 and C11) which shows:
EXAMPLE 1
int i1 = 1; // definition, external linkage static int i2 = 2; // definition, internal linkage extern int i3 = 3; // definition, external linkage int i4; // tentative definition, external linkage static int i5; // tentative definition, internal linkage
The example continues, but the
extern int i3 = 3;
line clearly shows that the standard indicates that it should be allowed. Note, however, that examples in the standard are technically not 'normative' (see the foreword in the standard); they are not a definitive statement of what is and is not allowed.That said, most people most of the time do not use
extern
and an initializer.这篇关于如何与声明一起定义外部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!