0

I get very confused with the static and extern storage classes. I do not understand what is wrong with the below code snippet. I expect the printf to print the value Zero. The build is failing with the error "Undefined reference to 'i' ". I expect the statement "extern int i" to be a valid C statement. Is it not?

#include<stdio.h>
void main()
{
 extern int i;
 printf("%d", i);
 }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Divya
  • 393
  • 2
  • 5
  • 17
  • http://stackoverflow.com/questions/21774492/what-is-a-concept-behind-using-extern-in-c-c this might be a good read – Ediac Jun 24 '15 at 06:33
  • "_I get very confused with the static and extern storage classes._" -- Indeed. Use `static` instead of `extern` to get the expected output. – Spikatrix Jun 24 '15 at 06:40

3 Answers3

1

In the function main

extern int i;

is a declaration of i, not definition. It must be defined somewhere.

#include<stdio.h>
int i;               //definition
int main()
{
    extern int i;    //declaration
    printf("%d", i);
}

In this example, the declaration is valid, but can be omitted.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1

When you declare a variable as extern inside a function, the compiler thinks that the variable is defined in some other translation unit. If it's not defined anywhere else, then you will get a linker error saying that the linker can't find the variable.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    Not necessarily in some other translation unit. It can be defined in same translation unit also. – cbinder Sep 12 '15 at 06:31
-3

see when you are using extern storage class in the main then our compiler use to search the declaration of the variable in the perticular location ,here extern stands for compiler that this variable is declared at any location in the program it can be local or outside the scope , if it dont found any declaration then it gives this linking error becoz it is unable to found the variable declaration.

Mukul
  • 114
  • 1
  • 11