views:

256

answers:

4

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.

+4  A: 

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.

R Samuel Klatchko
Almost: you cannot access it outside of that TU (translation unit). An understanding of TUs and realizing file-level static means "TU-local only" is what he needs.
Roger Pate
@Roger - you are absolutely correct. But I remember when I was a newbie C programmer that "translation unit" always confused me.
R Samuel Klatchko
+1. I like the usage of an accessor function here.
darren
+11  A: 

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.

AndreyT
+6  A: 

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
gameover
+1  A: 

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.

wrapperm