Have a look at the following code snippet…
File1.h
void somefunc(int);
File1.c
#include "File1.h"
extern int var;
void somefunc(int x)
{
......
var ++;
etc, etc,
....
return;
}
File2.h
static int var;
void someotherfunc(int);
File2.c
#include "File2.h"
#include "File1.h"
int var;
void someotherfunc(int z)
{
z = etc etc;
var --;
......
somefunc(z);
.....
return;
}
The above four files compile without any problem.
The problem occurs when i try to initialize the variable ‘var’.
If the ‘var’ is initialized in the File2.c where it is a global variable, the code compiles without any problems. But when i try to initialize the static variable in File2.h, the compiler throws an error saying ‘the variable ‘var’ in File1.c is undefined’. Can someone please tell what is happening here.
I was just trying to understand the concept of static variables and came upon this confusion. Any help would be appreciated.
This gives
varinternal linkage in the File2.c translation unit, whatever might follow (yes, even if theexterndeclaration follows).So if the first declaration seen is
static int var, in that translation unitvarwill forever be internal, thus inaccessible to other translation units.