Access a global static variable from another file in C
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.
Solution 1:
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.
Solution 2:
You can make the global variable pointer to the global static variable.
/* file a.c */
static int a = 100; /* global static variable not visible outside this file.*/
int *b = &a; /* global int pointer, pointing to global static*/
/* file b.c */
extern int *b; /* only declaration, b is defined in other file.*/
int main()
{
printf("%d\n",*b); /* dereferencing b will give the value of variable a in file a.c */
return 0;
}
On running:
$ gcc *.c && ./a.out
100
Solution 3:
You cannot access a file level static variable outside of the file.
If you truly need to do that, you have a couple of choices.
-
Add an accessor function to the file that has the static variable. The nice thing is this restricts access from outside the file to read-only access:
int read_static() { return val; }
Drop the static qualifier and make the variable a global.
Solution 4:
Solution 1:
In file a.c
static int val=10;
int *globalvar =&val;
In file b.c
extern int *globalvar;
Solution 2:
Instead of having another variable to pass the address of the static variable thereby adding few memory bytes wastage, make the static variable itself as extern.
Solution 2 is recommended, but in case if you are restricted to changing the static variable to extern, use solution 1.