extern storage class variable inside main function

104 Views Asked by At

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);
 }
3

There are 3 best solutions below

0
On

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.

1
On

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.

0
On

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.