Sunday, May 23, 2010

How to use an extern variable in C?



   Extern variable in C is an extension of global variable concept. First, let us see what is a global variable and the difference between a global variable and an extern variable.

What is a global variable?

       Any variable declared outside a function block is a global variable. A global variable  can be accessed by any function in the file in which it is defined. The scope of the global variable is throughout the file in which it is present. 
int globalVar;
   The variable globalVar is defined as a global variable for which memory space is allocated and the memory location is accessed by the name globalVar. Since there is no initial value specified, the variable gets initialized to zero. This variable can now be accessed from any function in the file in which this definition is present.

What is an extern  variable?

   Assume a scenario where you would like to access the global variable globalVar in another program. If you happen to declare a global variable with the same name in the second file, the compiler will not allow since no two variables can be declared with the same name.  So, how would you access the global variable globalVar defined in the first file? Simple, the answer to this is extern.
extern int globalVar;
  When you use extern keyword before the global variable declaration, the compiler understands you want to access a variable being  defined in another program or file, and hence not to allocate any memory for this one. Instead, it simply points to the global variable defined in the other file. In this fashion, you can use the extern keyword in any number of programs to access the global variable globalVar. However, the definition should only be at one place.

Let us see an example:

# cat f1.c
#include <stdio.h>

int globalVar=3;

void fun();

int main()
{
 fun();
 printf("Global var in f1 is %d\n", globalVar);
 return 1;
}
     The above file f1.c contains the main program in which a function fun is being called. The main point here is the definition of the variable globalVar. At this juncture, the globalVar is simply a global variable.

#cat f2.c
#include <stdio.h>

extern int globalVar;
void fun()
{
  printf("Global var in f2 is %d\n", globalVar);
  globalVar++;
}
     In the above file f2.c, the function fun wants to access the variable globalVar being defined in the file f1.c. In order to access the variable, the extern keyword is used for declaration of the globalVar variable and hence no memory is allocated for globalVar, instead it starts pointing to the globalVar in the f1.c .

# cc -o ser f1.c f2.c
# ./ser
Global var in f2 is 3
Global var in f1 is 4
#
  The files are compiled and an executable ser is generated. On running the executable ser, as shown above, the function in the file f2.c accessed the variable defined in the first file f1.c.

1 comment: