【发布时间】:2017-07-14 14:31:45
【问题描述】:
考虑以下几点:
// 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 %d\n", &_state, _state.b);
}
// App.hpp
#include "defs.h"
class App
{
App();
};
// App.cpp
#include "App.hpp"
App::App()
{
printf("1 state at %p is %d\n", &_state, _state.b)
t_state_allocate();
printf("2 state at %p is %d\n", &_state, _state.b)
}
G++ 下的输出是这样的:
0x736e20 处的 1 个状态为 0
0x9cb140 处的 G 状态为 1
0x736e20 处的 2 状态为 0
这里预期的行为是访问相同的结构..错误在哪里?
编辑 1
t_state 必须是纯 C struct,因为它用于其他 .c 源代码(因此是 extern 关键字)。但是我可以同意 没有人 修改它的内容。
【问题讨论】:
-
您 a) 在头文件中定义一个变量,并且 b) 将其定义为静态的 - 这很可能不会达到您的预期。而是在一个 C 源文件中定义它,并在
.hpp中将其声明为extern
标签: c++ c pointers global-variables