开发者

Accessing static variable value

开发者 https://www.devze.com 2023-01-21 00:23 出处:网络
I have a static variable in source file test_1.c declared as: static char var1 = 0; I need to access the current value of this variable from source file test_2.c. So, I did something like:

I have a static variable in source file test_1.c declared as:

static char var1 = 0;

I need to access the current value of this variable from source file test_2.c. So, I did something like:

In test_1.c

static char var1 = 0;
volatile char var_another = var1;

and in test_2.c, I declare the variable var_another as extern and access it:

extern volatile char va开发者_Python百科r_another;

Is this the right way to do it?


static and extern are mutually exclusive. If you want to access your static char var1 from a different file, you'll have to remove the static and just make it a regular global. You don't need volatile at all.

Alternatively, you can make an accessor function that returns the value of static char var1 and use that from your other module.

Side note: externs and exported function prototypes should generally go in header files.


No! The whole point of static (in this context) is that you're stating that the variable is only visible from this translation module.

If you don't want this behaviour, then don't declare it as static. Put char var1 = 0; in your source file, and extern var1; in the associated header file.

More generally, don't do this at all. Accessing global variables between source files is probably a recipe for disaster.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号