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

#include<stdio.h>

extern int a;

int main ()
{
  a = 5;
  return 0;
}
bosch@bosch-Inspiron-N5050:~$ gcc main.c
/tmp/ccj2b4DW.o: In function `main':
main.c:(.text+0x6): undefined reference to `a'
collect2: error: ld returned 1 exit status

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.

#include<stdio.h>

int a;

int main ()
{
  a = 5;
  return 0;
}

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

#include<stdio.h>
#include "myheader.h"

extern int a;

int main ()
{
  printf("The a is %d\n",a);
  return 0;
}

myheader.h

int a=-1;

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

#include<stdio.h>

int main ()
{
  // error ‘a’ has both ‘extern’ and initializer
  extern int a=4;
  return 0;
}

Ref:

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



Related Contents to follow