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.
file1:
file2:
There are two variables referenced here. The first is a declaration and definition of a variable with internal linkage in
file1; the second is a declaration only of a variable with external linkage infile2. This doesn’t necessarily cause an error; it is completely legal to have a variable with external linkage used in some translation units and identically named variables with internal linkage used by other translation units. Any link error would only occur ifais used infile2and there isn’t a definition for thisainfile2or any other translation unit in the program.In this example you have combined the two files into a single translation unit. The variable
ais first declared and defined infilewith internal linkage due tostatic, the second is just a re-declaration which doesn’t alter the previous linkage. The second declaration is redundant in this instance. If you are still compiling both files separately as well as includingfile1fromfile2then each translation unit (file1andfile1 + file2) will have its own distinct variable calleda.Note that if you had used
extern int a;followed bystatic int a;then this would be a compile error as the first declaration would declareato have external linkage if no previously declaration was visible and then the second declaration and definition would cause an error because the linkage implied bystatic int a;would conflict with the previous declaration.