What does extern REALLY mean?


While it’s often to see this:

extern int i;

the usage of ‘extern’ is not so obvious, and there is more.

Here is my question:
I have 1.cpp with this piece of code:

extern const int i;
int main()
{
	printf("%d", i);
}

How do you define i in 2.cpp so that the program links and runs? Answer is listed below.

This should be in 2.cpp

extern const int i = 2;

The key to understand it is that extern is for declaration, instead of definition.
extern declares the variable (and function) external linking.
However, it has a significant side effect,
which is taking away definition while leaving there only declaration. see this example:

extern int i; //here we are only taking advantage of extern's side effect.

The side effect works only if i is not initialized. Therefore

extern int i = 2; //this is definition. side effect does't work.

Now back to our original question. The code in 2.cpp is equivalent to this.

extern const int i; //declaration
const int i = 2; //definition

I hope now it’s all clear.

However, another question has been bothering me for long time. I need your help.
Is there a way to declare (without definition) a static variable?
So far my answer is no.

Advertisements