Alex Rivera | Logout

Access a global static variable from another file in C

Asked 2009-12-29T06:09:42.763
11

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.

Edit
Report

1 Answer

10

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
answered 2009-12-29T06:18:13.403

Your Answer