Access a global static variable from another file in C

旧城冷巷雨未停 提交于 2019-11-27 04:54:57

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.

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

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.

  1. 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; }

  2. Drop the static qualifier and make the variable a global.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!