访问静态变量的值 [英] Accessing static variable value
问题描述
我在源文件静态
变量 test_1.c时声明:
static char var1 = 0;
我需要从源文件中访问该变量的当前值 test_2.c 。所以,我不喜欢的东西:
I need to access the current value of this variable from source file test_2.c. So, I did something like:
在test_1.c时
static char var1 = 0;
volatile char var_another = var1;
和 test_2.c ,我宣布变量 var_another 为的extern
和访问:
and in test_2.c, I declare the variable var_another as extern
and access it:
extern volatile char var_another;
这是做正确的方式?
推荐答案
静态
和的extern
是互斥的。如果你想访问你的静态字符VAR1
从不同的文件,你就必须删除静态
和刚使之成为经常性全球。你不需要挥发性
的。
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.
另外,你可以让一个访问函数,返回静态字符VAR1的价值和使用,从您的其他模块。
Alternatively, you can make an accessor function that returns the value of static char var1
and use that from your other module.
旁注:externs和导出函数原型通常应该在头文件
Side note: externs and exported function prototypes should generally go in header files.
这篇关于访问静态变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!