Here is the code:
Code://file main.cc
#include "test.h"
int main(){
cout<<x;
}
Code://file test.h
static int x = 10;
This code works. But should static int x be local to test.h only? How come it can be used in a totally different file?
Printable View
Here is the code:
Code://file main.cc
#include "test.h"
int main(){
cout<<x;
}
Code://file test.h
static int x = 10;
This code works. But should static int x be local to test.h only? How come it can be used in a totally different file?
Do not define variables in header files. Define them in source files, ie .cpp files instead.
Yes, if you define a global variable with the "static" keyword, it means it will only be visible in the current source file. This can allow for some more compiler optimizations.
It can be used in a totally different file, but then it would be a distinct variable. So for example &x will not be the same, and if you change x in one file, it will not change in the other.
I see this is duplicate question for the same thing.
The answer is, just as in the other thread: header files are not compiled. Their contents are pasted into source files.