Why can't I initialize int foo = 7 in main |
Because the variable is declared to exist in the
global namespace, not as a local variable.
Writing
int foo = 7
inside the
main
function declares a local variable, entirely different than the one declared in
my.h and initialized in
my.cpp
If I was able to initialize foo in main, why initialize it in my.cpp? |
If you don't initialize a
extern
variable at the point of definition, it will be zero-initialized for you by the compiler before the program starts (ignoring thread-local variables for now.)
By this, I mean:
my.hpp
|
extern int foo; // declaration
|
my.cpp
1 2
|
# include "my.hpp"
int foo; // definition, but implicit initialization to zero
|
use.cpp
1 2 3 4 5 6 7
|
# include "my.hpp"
int main() {
// foo has already been zero-initialized here
std::cout << foo << '\n'; // prints 0
// assignment, not initialization -- foo already has a value.
foo = 7;
}
|
Why doesn't my.cpp end up printing foo == 0 ? How is print_foo passed foo == 7 in main() , and how does extern int foo factor in? |
The point is that foo is a global variable. There is only one, which is initialized to zero before the program starts, modified in
main()
, and then printed when
print_foo()
is called. This is the purpose of
extern
, which says that there is
exactly one variable named
foo
defined somewhere, only once.