Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 710
Sikandar Avatar asked Dec 29 '09 06:12

Sikandar


People also ask

Can we access global static variable in another file?

Static variables in C have the following two properties: They cannot be accessed from any other file. Thus, prefixes “ extern ” and “ static ” cannot be used in the same declaration. They maintain their value throughout the execution of the program independently of the scope in which they are defined.

How is a variable accessed from another file in C?

It is possible to create a global variable in one file and access it from another file. In order to do this, the variable must be declared in both files, but the keyword extern must precede the "second" declaration. global static variable is one that can only be accessed in the file where it is created.

Can a static variable be visible in several files?

Static — use the static keyword to make a global variable visible only to functions within the same source file whenever possible. This removes any potential for conflict with variables of the same name in any other library source files or user application code. You can use static and volatile together.

How do you access global variables?

Global Variable: The variable that exists outside of all functions. It is the variable that is visible from all other scopes. We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolution operator respectively.


1 Answers

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.

like image 77
AnT Avatar answered Oct 16 '22 03:10

AnT