This code will produce error in c++
// Foo.cpp
const int Foo = 99;
// Main.cpp
extern const int Foo;
int main()
{
cout << Foo << endl;
return 0;
}
Reason as given by many is global const has internal scope and it is default static.
solution to this is :-
//Foo.h
extern const int Foo;
// Foo.cpp
#include "Foo.h"
const int Foo = 99;
// Main.cpp
#include "Foo.h"
int main()
{
cout << Foo << endl;
}
I used to think that extern is used to tell compiler that memory for the indentifer is already allocated somewhere in other files.
Applying same logic on above code can anyone explain what is happening here or extern has different meaning in c++??
enter link description here
Also consider this page it is spoiling my all intuitions..
What if we have to declare only a global constant(not
static)? Howexternhelp in doing this?A
constobject declared withexternqualifier has external linkage.So if you want to use a
constacross multiple Translation units, add anexternqualifier to it.While a global variable has external linkage by default,why a const global has internal linkage by default?
Reference:
C++03 Standard Annex C Compatibility C.1.2 Clause 3: basic concepts
Avoid the confusion by following a simple rule:
By default Linkage is external for non-const symbols and static (internal) for const symbols.