C地址中的静态变量用法不同

Static Variable Usage In C Adress different

我有一个头文件,我在其中声明了一个结构并将其声明为

static Test_t = TESTID;

项目中有多个文件,文件有多种功能。并希望从不同的文件和函数更新这些变量。所以试图在每个函数中获取这个静态变量的地址,比如

Test_t *info = &TESTID;

更新为info-> ...

但是info的地址在功能上是不一样的?
可能是什么原因?

你基本上想要这样的东西:

Header.h

...
extern int thevariable;   // this only declares that thevariable exists
                          // somewhere else
...

file1.c

#include "Header.h"
...
int thevariable;     // declare the variable in one and only in one place
...
thevariable = 123;

file2.c

#include "Header.h"
...
thevariable = foo;  // refers to thevariable declared in file1.c

file3.c

#include "Header.h"
...
bar = thevariable;  // refers to thevariable declared in file1.c

为此你不需要(也不想要)静态变量。

首先使用 static 的主要原因之一是使变量在其声明的范围内成为局部变量。如果您在文件范围(在所有函数之外)声明它,那么它在声明它的翻译单元 中是本地的。一个翻译单元是指一个.c文件和.c文件包含的所有.h文件。

意味着如果你在 foo.h 中有一个 static 变量,那么 foo.c 和 bar.c 中有 #include "foo.h",那么你最终会得到两个该变量的不同本地副本:一个在翻译单元 foo.h + foo.c 内,另一个在翻译单元 foo.h + bar.c.

解决方案是从不在头文件中声明任何变量。除了上面描述的奇怪的问题之外,您还可以 运行 进入各种链接器错误。

一个明智的解决方案是只在 test.c 中包含 static Test_t test = TESTID;。然后从 test.h 中创建 setter 和 getter 函数,其他函数将使用这些函数来访问变量。

如果getters return副本或const指针和其他文件应该允许直接访问成员,则结构声明可以放在test.h中。或者更确切地说,这对于更简单的东西很好,但不推荐用于应该使用适当私有封装的更复杂的 ADT。

(这种设计的唯一缺点是它不是线程安全的,除非您在 setter/getters 内部实现线程安全,但那是另一回事了。)