A static variable has an area inside this file only where it was declared, as shown below:
file1 -
static int a;
file2 -
extern int a;
This will give a binding error, since the static variable a has scope only in file1. But I am confused below the code:
file2 -
#include "file1"
extern int a;
Here it will not give any binding error. Then this means that the compiler refers to "a", which is declared in file1. But when you debug, you will find that the address of the variable "a" is different in files1 and file2. Is the compiler creating another global variable "a" in file2?
full code -
file temp1.h -
static int w = 9;
class temp1
{
public:
temp1(void);
public:
~temp1(void);
void func();
};
........................ caste .................
temp1::temp1(void)
{
int e =w;
}
temp1::~temp1(void)
{
}
void temp1::func()
{
}
....................................... file2 -
#include "temp1.h"
extern int w;
int _tmain(int argc, _TCHAR* argv[])
{
w = 12;
temp1 obj;
return 0;
}
here, when I debug and check the value and adrress in constructor temp1, and in file2 it is different.