Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extern Variable

Tags:

c

int main()
{
  extern int i;
  i=20;
  printf("%d",i);
  return 0;
}

The compiler is giving an Error that 'i' is undefined

Whats the Reason?

like image 707
Abi Avatar asked Jan 11 '11 16:01

Abi


2 Answers

Difference :

1.int i; // i is defined to be an integer type in the current function/file
2.extern int i; // i is defined in some other file and only a proto-type is present here.

Hence while compiling, the compiler(LDD) will look for the original definition of the variable and if it does'nt find, it'll throw an error 'undefined reference to `i'.

like image 125
aTJ Avatar answered Oct 06 '22 14:10

aTJ


By saying extern you tell the compiler that i is defined in a different translation unit, which I'm guessing you don't have. There's a difference between declaration and definition in C. In short, the former is telling the compiler the type of the variable, the latter is telling to allocate storage for it.

Just drop that extern for now.

like image 39
Nikolai Fetissov Avatar answered Oct 06 '22 14:10

Nikolai Fetissov