Why do variables need to be externed at declaration in header file and then declared again in the corresponding cpp file to:
a. Prevent Link error
ex. header 1.h-
namespace forglobal {
extern int x;
}
source 1.cpp-
namespace forglobal{
int x=6;
}
source 2.cpp-
#include "1.h"
cout<<x; //6
b. Use in different cpp files, can't I just use the namespace like I call a function ex.
header -1.h
namespace forglobal {
int x
}
source -1.cpp {
namespace forglobal {
void change() {
x=5;
}
}
}
source -2.cpp
#include "1.h"
forglobal::change();
cout<<forglobal::x<<'\n'; //5
Any namespace-level variable declaration which isn't declared extern
is also a definition. That is, if you have header with a non-extern
variable declaration which is included in more then one translation unit linked into a program, you get multiple definitions. To prevent that, you mark the variable declaration in the header as extern
and omit the extern
where the definition is located.
Of course, using global variables is generally a Bad Idea in the first place but that's a different discussion.