It's all about the linkage.
The previous answers provided good explanations about extern
.
But I want to add an important point.
You ask about extern
in C++, not in C and I don't know why there is no answer mentioning the case when extern
comes with const
in C++.
In C++, a const
variable has internal linkage by default (not like C).
So this scenario will lead to linking error:
Source 1 :
const int global = 255; //wrong way to make a definition of global const variable in C++
Source 2 :
extern const int global; //declaration
It needs to be like this:
Source 1 :
extern const int global = 255; //a definition of global const variable in C++
Source 2 :
extern const int global; //declaration
extern
on several occasions. Microsoft tools produced a link error for missing symbols when the tables in another source file were only defined. The problem was, the table wasconst
and the C++ compiler promoted it tostatic
in the translation unit. See, for example,ariatab.cpp
andkalynatab.cpp
.inline
may be a better way to accomplish what you want to do withextern
. Withinline
, you can define globals in headers and not worry about multiple definition problems. stackoverflow.com/questions/38043442/…