C中同名的外部变量和全局变量

extern and global variables with the same name in C

我想弄清楚如果在某些程序中我们会有这样的情况会发生什么:

extern int x;

void foo(){...}
void bar(){...}

void main(){
foo();
bar();
}
int x=0;

那么假设会发生什么?为什么允许有两个这样的同名变量?它们不同吗?

"extern"表示:
"this variable will come from some other place. It is not being declared here; this statement just provides notice that it is a valid name."

所以本质上这段代码是:

extern int x;
// This is a valid name, but the variable will be defined "externally", eg, somewhere else.

[...] 

int x=0;
// OH!  Here is where the definition is.  Now we know where that "extern" variable came from.
// And we know that it starts with value 0.

and extern 和定义出现在同一个文件中有些不寻常。

更典型的是,定义在一个 .C 文件中,而 extern 在不同的 .C 中,它们将在构建过程中链接在一起。

它们不是 "two" 变量。他们是一样

extern int x;

x的声明。

int x=0;

提供 x 的定义。这是完全正确和有效的。


您可以有多个声明,例如:

extern int x;
extern int x;

也是,它也会编译。

请注意,当您为同一标识符提供多个声明时,规则会有些复杂。有关详细信息,请参阅:6.2.2 Linkages of identifiers。 有关示例,请参阅 static declaration of m follows non-static declaration

非常好。 这个

extern int x;

只声明了 int 类型的变量 x,extern 明确表示,它将在另一个位置定义。

在你的情况下,下面几行

int x = 0;

这里是 link 有关 extern 的更多信息 -> http://en.cppreference.com/w/cpp/language/storage_duration

The extern specifier is only allowed in the declarations of variables and functions (except class members or function parameters). It specifies external linkage, and does not technically affect storage duration, but it cannot be used in a definition of an automatic storage duration object, so all extern objects have static or thread durations. In addition, a variable declaration that uses extern and has no initializer is not a definition.