extern keyword usage

anu picture anu · Jul 28, 2011 · Viewed 13.9k times · Source

I have three programs in which I am using extern keyword. I am not able to understand the result. Below are three examples:

Example 1: I was expecting that below code will give compilation error that multiple declaration of k. But it works fine?

int k; //works fine
extern int k = 10;

void main()
{
    cout<<k<<endl;
    getchar();
}

Example 2: When I am trying to initialize "k" in above example compiler gives error. Why?

int k = 20; //error
extern int k = 10;

void main()
{
    cout<<k<<endl;
    getchar();
}

Example 3: In this example I changed the order of definitions mentioned in example 1. When I compile this code I am getting errors. Why?

extern int k = 10;
int k;   //error

void main()
{
    cout<<k<<endl;
    getchar();
}

Answer

Didier Trosset picture Didier Trosset · Jul 28, 2011

Example 2: You are trying to initialize a global variable twice, with two different values. This is the error.

Example 3: You first declare an extern variable, and then define a variable with the same name in the same compilation unit. This is not possible.