[英]Is there any way to access static global variable defined in main.c and modify it in another file?
For example:例如:
In main.c
在
main.c
static glob_var;
I want to modify the value of glob_var in another file say file1.c
我想在另一个文件中修改 glob_var 的值,比如
file1.c
Making an variable static
makes its identifier inaccessible from other translation unit (what usually means other C-file).将变量
static
会使其他翻译单元(通常意味着其他 C 文件)无法访问其标识符。 You can either你可以
//main.c
int glob_var;
//file1.c
extern int glob_var;
Note that the declaration should be put to a header file.请注意,声明应放在头文件中。
//main.c
static int glob_var;
void SetGlobVar(int val) {
glob_var = val;
}
//file1.c
void SetGlobVar(int);
void foo(void) {
SetGlobVar(42);
}
Note that the declaration of SetGlobVar()
should be put to a header file.请注意,
SetGlobVar()
的声明应放在头文件中。
The comments and other answer address the question of how to access and modify a static global" . The following is offed as an alternative to using static for this purpose...评论和其他答案解决了如何访问和修改静态全局“的问题。以下是为此目的使用静态的替代方法......
When needing to create a variable that is global and can be changed among several translation units I believe it is more idiomatic to use the extern
storage class .当需要创建一个全局变量并且可以在多个翻译单元之间进行更改时,我相信使用
extern
存储类更为惯用。 This is typically done by:这通常通过以下方式完成:
#includes
s the header file.#includes
头文件的 .c 文件中一次性定义extern 变量。#include
s the header file in which the extern
is declared.#include
是声明extern
的头文件。 Example:例子:
in some.h
:在
some.h
中:
void modify_glob_var(int val);
...
extern int glob_var;//declare extern variable
in main.c
在
main.c
#include "some.h"
...
int glob_var = 0;// define extern variable
...
modify_glob_var(10);//access and modify extern variable
in some_other.c
在
some_other.c
include "some.h"
...
void modify_glob_var(int val)
{
glob_var = val;//value of extern glob_var is changed here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.