0

Consider the following:

// 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)
}

Output under G++ is something like:

1 state at 0x736e20 is 0

G state at 0x9cb140 is 1

2 state at 0x736e20 is 0

Here the expected behaviour is to access the same structure.. Where's the mistake ?

EDIT 1

t_state must be a pure C struct because it is used in other .c source code (and thus the extern keyword). However I can grant that nobody modifies its content.

Community
  • 1
  • 1
Patrizio Bertoni
  • 2,582
  • 31
  • 43

2 Answers2

1

In your code, you have two different global variables: one at App.cpp including defs.h, and the other one at defs.cpp including defs.h.

You have to use extern as you can see here:

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

lilezek
  • 6,976
  • 1
  • 27
  • 45
1

defs.h is included twice in two different .cpp files. so there are two instances of _state getting created. This is because #include essentially pastes the contents of the header into the file that includes it. So how do you get around this problem? Use extern:

typedef struct t_state
{
   bool b;
} t_state;

extern t_state _state; //Tells the compiler to share the variable between files.

Now you can use the variable in each source file:

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