I have a header file called abc.h in which i want to define a constant with an external linkage. Thus it contains the statement
---------------abc.h-------------------------
extern const int ONE = 1;
Next, i have main.cpp, where i want to use the value of ONE. Thus i declare the ONE in main.cpp before using it as
---------------main.cpp---------------------
extern const int ONE;
int main()
{
cout << ONE << endl;
}
I get an error "Multiple definition of ONE".
My question is , how can i declare a const with external linkage, and use it subsequently in different files, such that there is ONLY one memory location for the constant as opposed to each file containing a static version of the constant.
I deleted the #include "abc.h" from main.cpp and everything works.
g++ abc.h main.cpp -o main
The address of ONE is same in header and the main. So it works.
But i dont understand how compiler resolves definition of ONE without include statement in the main.cpp
It seems like g++ does some magic. Is it a bad practice, where reader of main.cpp does not know where ONE is declared as there is no include "abc.h" in main.cpp ?