View Single Post
Old Jun 22nd, 2005, 3:58 PM   #1
earl
Newbie
 
Join Date: Jun 2005
Posts: 18
Rep Power: 0 earl is on a distinguished road
static class members and libraries (linking question)

OK I have to apologize in advance for this obscure question, but hopefully somebody can point me in the right direction...

Consider a class with a static member, initialized in that class' header file. i.e.,

// Obj.h
class Obj
{
  ...
  static int num;
  ...
};

Obj::num = 3;

Now assume this header is included in various places of an application, as well as runtime libraries loaded by that application. In terms of the entire process, will there exist one single Obj::num, or will each module have its own copy of Obj::num?

I've been doing related testing, and I'm confused because I've seen both behaviors, but I can't narrow down what causes each. I've been trying different ways of building shared libraries (i.e., using ld myself, using g++ -shared, etc.). Is there a C++ language mechanism I can use to explicitly force the "single copy for the entire process" scenario, despite how the application and its modules are compiled/linked? For instance, changing my header to:

// Obj.h
class Obj
{
  ...
  static int num;
  ...
};

#ifdef MAIN_MODULE
Obj::num = 3;
#endif

I presume would only declare num in my main module (assuming I define MAIN_MODULE for that compilation), but I'm not familiar enough with what's happening behind the scenes to know if this is correct. I would like a way to code this so I don't have to worry about how it is compiled and linked on a bunch of different UNIX platforms. Any insight (or directions to any related linking tutorials) is appreciated...
earl is offline   Reply With Quote