extern keyword in c programming language is a keyword which directs the compiler that a variable prefix with extern is only a declaration. I think somebody who will read this post may think what makes me to post this article even if there are lots of already published articles are on Internet. Every body is not a great developers. I am a average developers and there are number of developers like me who forget the tiny and important facts about c programming. so it is better to learn facts by making errors and latter on by solving it.  isn’t  it a good way to learn facts?

extern keyword in c programming

Here compilation fails. it is giving undefined reference to a. it means compiler is unable to find the definition of declared variable a inside our program. Now let us removed the keyword extern from the above example and try to build.

The above code would compile without any error. so now we can say that declaring a variable prefixed with extern keyword tells the compiler that it is only declaration and do not initialize it.

extern keyword in c programming interview questions

  • Why by default global variables in c is extern?

Let us see below example.

main.c

myheader.h

extern-keyword

The extern declaration of variable a in file main.c instructs compiler that its definition is somewhere else. The compiler find the definition of variable a in file myheader.h during building and linking program. when compiler sees a global variable it inserts extern keyword implicitly to the global variable.

  • can you initialize extern locally?

Ans: no , for example below code would not compile

Ref:

https://en.wikipedia.org/wiki/External_variable