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

标签 c global external extern

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

extern int x;

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

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

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

最佳答案

它们不是“两个”变量。它们相同

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举个例子。

关于c - C中同名的外部变量和全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42124371/

相关文章:

c++ - Unresolved external 使用 QT Creator

javascript - 这些 window.external 调用是什么意思?

jquery:如何将其他 .js 文件包含到 .js 中

c - "scrolling range"是什么意思?

c - 如何读入文本文件中的最后一个单词并读入 C 中的另一个文本文件?

c - 使用C在Linux中通过串口从SIM读取短信

python - python中带有setdefault的全局变量

python - 在 Python 中使用 C 类型

c++ - 未命名的命名空间与全局声明

c++ - QTQuick设计: how to have a global class available from both C++ and QML?