the ‘extern’ keyword in C


The ‘extern’ keyword specifies that the object is declared with external linkage somewhere else in the program.

By preceding a variable name with ‘extern’ , you can declare a variable without defining it. When you need to
refer to a variable that is defined in another part of your program, you can declare that variable using
extern.

    EXAMPLE 1


#include

int main(void)
{
extern float first, last; /* using global vars */
printf(“%f %f”, first, last);
return 0;
}
/* global definition of first and last */
float first = 10.23, last = 20.33;


This program will 10.23 20.33 because the global variables first and last used by the printf( )
statement are initialized to these values. The extern declaration will tell the compiler that first
and last are declared somewhere else (outside main), so the program will be compiled without error.

Extern allows you to declare a variable without defining it. However, if you give that
variable an initialization, the extern declaration becomes a definition.

“Definition” refers to the place where the variable is created or assigned storage; “declaration” refers to the place where nature of variable is stated but no storage is allocated.

Advertisements