Suppose I created a header file constants.h and this file contains:
extern const int YEAR = 2011; // definition
If I tried in a cpp file (MainCPP.cpp) to use this constant after declaring it without defining it and without including the constants.h file as following:
extern const int YEAR; // declaration
int main() {
cout << YEAR << endl;
}
When I try to do that I get: unresolved external symbol “int const YEAR”. On the other hand, if I placed the definition of YEAR within constant.cpp file and done the same in MainCpp.cpp, I will not get the error and the linker will be able to link with YEAR defined within constants.cpp (without including constants.cpp in MainCpp.cpp here too).
Does this mean that the linker can link with source file code but not with header file code unless you explicitly included the header file.
externtells the compiler that space is allocated for it somewhere else. There must be a definition of it somewhere without an extern on it. BUT in C++ (unlike C), consts have internal linkage, so you don’t need the extern on it. (see Why does const imply internal linkage in C++, when it doesn't in C?)Just put
const int YEAR = 2011;in your header file and include your header file where ever you need it.