0

Possible Duplicate:
Redefinition allowed in C but not in C++?

#include<stdio.h>
int i;
int i;
int main()
{
        // int i;
        // int i;
        printf("%d\n",i);
        return 0;
}
~          

The above code runs wihtout giving any error gcc -Wall -Werror demo.c -o demo

But when I uncomment the local i variables the comment out the global i ,It gives me errors .

In function ‘main’:
demo.c:7:6: error: redeclaration of ‘i’ with no linkage
demo.c:6:6: note: previous declaration of ‘i’ was here

What is this local global concept here ?, Anybody Please explain.

Community
  • 1
  • 1
Omkant
  • 9,018
  • 8
  • 39
  • 59

2 Answers2

2

In C99 (see more specifically section 6.2), global declarations have by default external linkage (6.2.2§5). In that case (6.2.2§2), both declarations of i refer to the same object. On the contrary, local variables have no linkage (6.2.2§6), and are thus supposed to refer to unique identifiers (again 6.2.2§2): you would thus end up with two local variables of the same name in the same scope, which is not allowed (6.2.1§5: Different entities designated by the same identifier either have different scopes, or are in different name spaces)

Virgile
  • 9,724
  • 18
  • 42
1

You can have more than one definition of your variable in a global scope, if all definitions agree (all have the same type) and the variable is initialized in not more than one place.

J.5.11 Multiple external definitions

There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword extern; if the definitions disagree, or more than one is initialized, the behavior is undefined (6.9.2).

halex
  • 16,253
  • 5
  • 58
  • 67