-1

I have C++ that follows this pattern in an include file:

#ifdef MYHEADER
extern ClassA globalA;
#endif
#ifndef MYHEADER
#define MYHEADER
class ClassA {
    // code for ClassA
    };
static ClassA globalA;
#endif

The desire is to have only one instance of ClassA (globalA) where it is defined only in the header file. This is old code that I'm trying to clean up without making mass changes.

The problem I'm seeing is that in the debugger there are (at least) two different instances of globalA (two different addresses). I searched for other declarations and even commented out the static declaration to make sure I get a link error (I did). This code is threaded.

Is this a valid pattern? What might I misunderstood? Is there a better way to do this (without requiring changes to all references of globalA) ?

Dweeberly
  • 4,668
  • 2
  • 22
  • 41

1 Answers1

1

You pattern does not do what you think it does.

Translation units are compiled independently of each other. Every translation unit that wants to use globalA will need to know what ClassA is defined as. So, each time a given translation unit is compiled, MYHEADER will not be defined until your header file defines it, and as such every translation unit will end up seeing the static declaration, so every translation unit will get its own local copy of globalA, which is not what you want.

To do what you are attempting, you need to

  • get rid of the #ifdef block altogether.
  • replace the static declaration with the extern declaration.
  • move the globalA variable instance to one of your cpp files.

MyHeader.h

#ifndef MYHEADER
#define MYHEADER
class ClassA {
    // code for ClassA
    };
extern ClassA globalA;
#endif

MyHeader.cpp

#include "MyHeader.h"
ClassA globalA;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770