Access a global static variable from another file in C

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.

Leave a Comment