Static variable has the scope inside that file only where they are been declared, as shown in below code:
file1-
static int a;
file2-
extern int a;
This will give linking error as static variable a has the scope in file1 only. But I am confused with below code:
file2-
#include "file1"
extern int a;
Here it would not give any linking error. Then it means compiler is refering "a" which is declared in file1. But when you debug you will find address of variable "a" is different in file1 and file2. Is the compiler creating a another global variable "a" in file2?
complete code-
file temp1.h -
static int w = 9;
class temp1
{
public:
temp1(void);
public:
~temp1(void);
void func();
};
........................cpp.................
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 temp1 constructor and in file2 is different.
temp1.his including itself, that code isn't complete (or possibly isn't correct). Can you show the contents oftemp1.h?whas internal linkage due to the first declaration ofwbeing thestatic int w = 9;declaration included from the header file. This mean that both translation units have their own distinct independentw.externwithout an initializer is never a definition. If the object has previously been declared then the linkage is taken from the previous declaration (in this case internal), if no previous declaration exist then the object has external linkage. The only definition in both translation units comes from thestaticdeclaration in the header file.