C/C++全局变量唯一性



请考虑以下事项:

// defs.h
extern "C" {
typedef struct t_state
{
bool b;
} t_state;
static t_state _state;
void t_state_allocate();
}
// defs.cpp
#include "defs.h"
void t_state_allocate()
{
_state.b = true;
printf("G state at %p is %dn", &_state, _state.b);
}
// App.hpp
#include "defs.h"
class App
{
App();
};
// App.cpp
#include "App.hpp"
App::App()
{
printf("1 state at %p is %dn", &_state, _state.b)
t_state_allocate();
printf("2 state at %p is %dn", &_state, _state.b)
}

G++ 下的输出如下所示:

0x736e20 处的 1 个状态为 0

0x9cb140时的 G 状态为 1

2 0x736e20的状态为 0

这里的预期行为是访问相同的结构。错误在哪里?

编辑 1

t_state必须是纯 Cstruct,因为它用于其他.c源代码(因此是extern关键字)。但是,我可以承认没有人修改其内容。

在你的代码中,你有两个不同的全局变量:一个在 App.cpp包括 defs.h,另一个在 defs.cpp包括 defs.h。

您必须使用extern,如下所示:

如何使用 extern 在源文件之间共享变量?

defs.h 在两个不同的.cpp文件中包含两次。 因此,有两个_state实例正在创建。这是因为#include实质上是将标头的内容粘贴到包含它的文件中。那么如何解决这个问题呢?使用extern

typedef struct t_state
{
bool b;
} t_state;
extern t_state _state; //Tells the compiler to share the variable between files.

现在,您可以在每个源文件中使用该变量:

#include "defs.h"
void t_state_allocate()
{
_state.b = true;
printf("G state at %p is %dn", &_state, _state.b);
}

最新更新