c - 多个定义在 gcc 或 clang 中都不会给出错误或警告

标签 c gcc compilation clang warnings

如果我这么做了

#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/

相关文章:

无法使用 mbedtls 示例客户端连接到 https 服务器

c - 错误: conflicting types for 'functiono'

ios - libc++abi.dylib : handler threw exception -- but no stack trace in XCode

c - 结构体保存到 bin 文件后如何删除其内容?

c - 为什么我的 Makefile 构建了一个不存在的源文件?

c++ - 将 opencv 库添加到自定义库,ipp 出错?

python - 当客户端愉快地发送它们时,为什么 TCP 数据包总是无法到达服务器?

c - Android.mk 根据文件更改本地 C 包含目录

c++ - 为什么此代码片段会在 C 和 C++ 中生成截然不同的汇编代码?

c# - 无法在 Roslyn 的新 nuget 中获取方法 SyntaxTree.ParseFile?