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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With