Access a global static variable from another file in C

Sikandar picture Sikandar · Dec 29, 2009 · Viewed 31.5k times · Source

In C language, I want to access a global static variable outside the scope of the file. Let me know the best possible way to do it. One of the methods is to assign an extern global variable the value of static variable,

In file a.c

static int val = 10;
globalvar = val;

In file b.c

extern globalvar;

But in this case any changes in val(file a.c) will not be updated in globalvar in (file b.c).

Please let me know how can I achieve the same.

Thanks, Sikandar.

Answer

AnT picture AnT · Dec 29, 2009

Well, if you can modify file a.c then just make val non-static.

If you can modify a.c but can't make val non-static (why?), then you can just declare a global pointer to it in a.c

int *pval = &val;

and in b.c do

extern int *pval;

which will let you access the current value of val through *pval. Or you can introduce a non-static function that will return the current value of val.

But again, if you need to access it from other translation units, just make it non-static.