cbhavi
cbhavi

Reputation: 3

C - Static variable masking global variable

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.

Upvotes: 0

Views: 518

Answers (2)

paxdiablo
paxdiablo

Reputation: 881103

It can't be static. Static means its "visibility" (not the official term but probably more understandable) is limited to the C source file it appears in (in this case, that's File2.c).

That means, when you try to link together File1 and File2, the linker will not be able to see var in File2, which is why you're getting the error.

If you want it accessible from File1.c, ditch the "static" bit. In fact, since you already have var defined in File2.c, ditch the entire line from File2.h.

Upvotes: 2

cnicutar
cnicutar

Reputation: 182619

static int var;

This gives var internal linkage in the File2.c translation unit, whatever might follow (yes, even if the extern declaration follows).

So if the first declaration seen is static int var, in that translation unit var will forever be internal, thus inaccessible to other translation units.

6.2.2-4

For an identifier declared with the storage-class specifier extern [File1.h] in a scope in which a prior declaration of that identifier is visible [the one in File2.h] if the prior declaration specifies internal or external linkage [it specifies internal], the linkage of the identifier at > the later declaration is the same as the linkage specified at the prior declaration.

Upvotes: 2

Related Questions