GCC如何处理变量重定义

How does GCC handle variable redefinition

我写了一段这样的代码

int a;
int a = 100;
int main()
{
}

它被 GCC 编译成功,但被 G++.

编译失败

我想 GCC 通过忽略变量 a 的第一个定义来处理这个问题。但我想知道准确的规则,这样我就不会错过任何东西。

谁能帮帮我?

C

int a;  /* Tentative definition */
int a = 100; /* Definition */

来自 C11 规范中的 6.9.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.

int i4; // tentative definition, external linkage
static int i5; // tentative definition, internal linkage

在 C++ 中

int a;是一个定义(不是暂定的),因为一个对象有多个定义是非法的,所以不会编译。