【问题标题】:C/C++ global variable uniqueness?C/C++ 全局变量唯一性?
【发布时间】: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


【解决方案1】:

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

您必须使用extern,如您在此处看到的:

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

【讨论】:

    【解决方案2】:

    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 %d\n", &_state, _state.b);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      • 2012-01-07
      相关资源
      最近更新 更多