I am very very sorry. I didn\'t know my incomplete code attachment would create such a mess. I am very glad to see so many sincere helps.
This code will compile:
First, according to your comment, the file containing the main function has the definition static int main_stat = 10;
. You should be aware that this is not
the same variable as you defined in the file containing myadd
because as static variable its scope is restricted to that file. Indeed, thanks to that static variable with the same name, main
is not able to access the variable you defined in this file.
But that doesn't mean that either variable was created on the stack. Both are separate global variables, it's just that the variable main_stat
in the file containing main
(I'll call that file main file for short, and this one myadd file) is not available in any other file, while the variable main_stat
you defined here can be accessed from any file which contains the declaration extern main_stat;
(note: without initializer!). The main file cannot contain this declaration, however, because it would conflict with the static variable of the same name.
Note that giving an initializer makes your declaration of the variable a definition, that is, it's the same as if you had omitted the extern (note however that if a variable is declared constant, the extern may not be omitted because constants are by default static). The only global extern declarations which are not also definitions are those with extern, but without initializer.