Search code examples
cextern

Understanding `extern` storage class specifier in C


Consider given C codes :

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

It gives Compilation error. While if I initialize extern int i=10; then output is 10.

#include<stdio.h>
extern int i=10; //initialization statement
int main(){
    printf("%d", i);
    return 0;
}

And also, if I assign int i=10;then output is 10.

#include<stdio.h>
 extern int i;
 int i=10;  //assignment
int main(){
    printf("%d", i);
    return 0;
}

And

#include<stdio.h>
 extern int i;
 int main(){
    int i=10;   //assignment
    printf("%d", i);
    return 0;
}

Variation :

#include<stdio.h>
 extern int i;
 int i=20;
 int main(){
    int i=10;
    printf("%d", i);
    return 0;
}

Since, int i is local variable, so output is 10.

Please, can you explain some important point about extern storage class in C


I read somewhere, a declaration declares the name and type of variable or function. A definition causes storage to be allocated for the variable or the body of the function to be defined. The same variable or function may have many declaration, but there can be only one defition for that variable or function.


Solution

  • Consider

    int i;
    

    declared outside all the functions of the programme including main.

    This means i will have

    • file scope
    • static storage duration
    • space is allocated for i. #This is important.

    Consider

    extern int i;
    

    declared outside all the functions of the programme including main.
    This means i will have

    • file scope
    • static storage duration
    • i is only declared, not defined which means space is not allocated.
    • i is assumed to be defined somewhere else, may be, in an include file

    Consider

    extern int i=10; 
    

    declared outside all the functions of the programme including main.
    This is the case where you're initializing the extern variable i. In this case

    • Space is allocated for i.
    • i will be initialized to 10.
    • The keyword extern is neglected which means i is NOT declared only.

    Note

    For extern int i it is mandatory that the variable should be defined somewhere else, ie in another source file. If this is not the case, you will a compile-time error.