与extern关键字用法有关的疑问 [英] Doubt related to extern keyword usage

查看:107
本文介绍了与extern关键字用法有关的疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AFAIK,应使用extern关键字进行声明,并且不能将任何值与使用extern关键字声明的变量关联.但是假设我写的是这样的语句

AFAIK, extern keyword should be used for declaration and no value can be associated with the variable being declared with extern keyword. But supposing I write a statement like

extern int i = 10;

编译器是否应该为相同的错误标记?我看到一些编译器可以容忍而忽略了这一点吗?为什么会这样呢? "C"标准对此有何说明?

Should the compiler flag an error for the same? I have seen some compilers being tolerant and ignoring this? Why is this so? What does the 'C' standard says about this?

@全部,感谢您的回答.我仍然有疑问.假设我在另一个文件(例如a.c)中没有外部链接的情况下定义了此变量,然后在b.c中添加了此语句.编译器不标记错误还可以吗?是否需要重新定义?

@All, Thanks for the answers. I have a doubt still though. Suppose I have the definition for this variable without the extern linkage in another file say a.c and I add this statement in b.c. Still is it Ok for the compiler not to flag an error? Does it come under redefintion?

推荐答案

这是有效的语法,在C99标准中甚至有一个本质上相同的示例. (请参阅第6.9.2-4节.)

That's valid syntax, there is even an essentially identical example in the C99 standard. (See §6.9.2-4.)

的确,这些示例不是规范性的,但我认为这些示例旨在成为合法的语法.编译器通常会输出警告,因为它实际上并没有完成任何事情.

It's true that the examples are not normative but I believe it was intended to be legal syntax. The compiler will often output a warning, because it doesn't really accomplish anything.

4示例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
int i1;                 // valid tentative definition, refers to previous
int i2;                 // 6.2.2 renders undefined, linkage disagreement
int i3;                 // valid tentative definition, refers to previous
int i4;                 // valid tentative definition, refers to previous
int i5;                 // 6.2.2 renders undefined, linkage disagreement
extern int i1;          // refers to previous, whose linkage is external
extern int i2;          // refers to previous, whose linkage is internal
extern int i3;          // refers to previous, whose linkage is external
extern int i4;          // refers to previous, whose linkage is external
extern int i5;          // refers to previous, whose linkage is internal

这篇关于与extern关键字用法有关的疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆