Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does GCC handle variable redefinition

Tags:

c++

c

gcc

g++

I wrote a piece of code like this

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

It was compiled successfully by GCC, but not by G++.

I guess GCC handle this by ignoring the first definition of variable a. But I want to know the precise rule so that I won't miss anything.

Can anyone help me out?

like image 573
delphifirst Avatar asked May 26 '15 10:05

delphifirst


1 Answers

In C

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

From 6.9.2 External object definitions in C11 specs:

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

In C++

int a; is a definition (not tentative) and because it is illegal to have multiple definitions of an object, it will not compile.

like image 87
Mohit Jain Avatar answered Sep 28 '22 20:09

Mohit Jain