gpt4 book ai didi

c++ - C/C++ 全局变量唯一性?

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:35 24 4
gpt4 key购买 nike

考虑以下几点:

// 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++ 下的输出是这样的:

1 state at 0x736e20 is 0

G state at 0x9cb140 is 1

2 state at 0x736e20 is 0

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

编辑 1

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

最佳答案

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

您必须使用 extern,如您所见:

How do I use extern to share variables between source files?

关于c++ - C/C++ 全局变量唯一性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45105497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com