mark posted:
compiler g++ on linux
file.h has the following, int x=5;
and inside the main program file I can access "x" without declaring it
"extern x". Program compiles and runs fine....
also program compiles and runs fine with x declared as extern.
So is it necessary to declare x as extern if one get away without
declaring it extern ? What is the standard and good practice ?
First of all, let's say you have a CPP file as so:
#include "blah.hpp"
int main(void)
{
some_variable = 7;
}
After the preprocessor has processed that, you'll have a translation unit:
extern int some_variable;
int main(void)
{
some_variable = 7;
}
Now, the thing here is that no variable is declared at all!! The "extern"
says "Don't actually make a variable. There's already one made somewhere
else in some other CPP file. Compile *ME*, _this_ CPP file, and then let the
linker bother with finding out where the variable was actually declared!"
So our CPP file gets compiled. Now, somewhere else, you _MUST_ have CPP file
containing:
int some_variable;
So now, the linker takes all your translation units, which the compiler has
turned into object files, and sorts it all out.
If you DON'T want a particular variable to be visible outside of your CPP
file, then:
static int some_variable;
In this case, you won't get a compile error at all, but a Link errror, the
linker can't find the variable to which your "extern" statement refers.
-JKop