空调
extern int x;
int x = -22;
int main(){}
公元前
void mai();
int x = 100;
void mai(){}
gcc A.c B.c -> gives multiple definition Error
空调
extern int x;
int x = -22;
int main(){}
公元前
void mai();
int x;
void mai(){}
gcc A.c B.c -> Runs perfect.
有人可以解释一下吗?
最佳答案
这是由于“暂定”规则:
[C90: 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 specifierstatic
, 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.
这就是说你在 B.c 中的 x
有文件作用域,所以它不会与 A.c 中的 x
冲突。
请注意,此规则在 C++ 中不存在;这是 C 和 C++ 不同的一个例子。
关于c - 同一文件中的外部和全局相同变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21505021/