如果我这么做了
#include <stdio.h>
int a; //definition
int a; //definition
int a; //definition
int a; //definition
int a; //definition
int main() {
return 0;
}
例如,尽管多次定义了一个变量,但我不会从 gcc 或 clang 收到任何错误或警告。为什么?我以为我可以多次声明一个变量,但只能定义一次?
最佳答案
这是一个暂定的定义。也就是说,没有初始化程序的文件范围变量的每个声明都被视为声明而不是定义。该定义在翻译单元末尾隐式生成,初始值设定项等于 0。
来自 C 标准(6.9.2 外部对象定义)
2 A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.
关于c - 多个定义在 gcc 或 clang 中都不会给出错误或警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64344315/