Patrizio Bertoni Patrizio Bertoni - 3 years ago 361
C Question

C/C++ global variable uniqueness?

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.

Answer Source

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download