c - 同一文件中的外部和全局相同变量

标签 c

空调

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 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.

这就是说你在 B.c 中的 x 有文件作用域,所以它不会与 A.c 中的 x 冲突。

请注意,此规则在 C++ 中不存在;这是 C 和 C++ 不同的一个例子。

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

相关文章:

计算字符串中小写字母单词的数量 - C 编程

c - 我无法输入字符。我的程序终止

c# - 如何制作自己的图形界面?

c - 忽略一个特定文件的错误

c - 为什么第二个 printf 打印垃圾值

C 控制台应用程序和 Qt gui 之间的通信

c - 修改存在缓冲区溢出漏洞的C函数的返回地址

c - 对于C,我是否可以得出结论:函数声明中的 "Abstract Declarators"不是强制的,而是建议的?

c++ - 让 VC 调试器在堆栈溢出中显示更多帧

c - 牛顿-拉夫逊算法