c++staticstatic-linkingdynamic-linkingextern

What exactly is static variable behaviour in multiple linkeage of a library that contains it in C++?


Lets imagine a scenario where I have

Both A and B are linking C and include its header files. Now in C exist a class:

class Foo {
   static const Bar& getShared(); // just defined in cpp returning _sharedVarible
   static Bar _sharedVarible; // defined in cpp
};

Does it mean that in this scenario I will have multiple copies of sharedVariable within A and B, if I call getShared() in each of them?

If C is also a .dll then would be the situation same, or as C is dll I have just one unique instance of that sharedVariable for both A and B?

And the last one - if both scenarios result in multiple copies of that variable is this solution where C is still .lib:

// in some header of C...
extern Bar sharedVariable;

// in some cpp of C...
sharedVariable = Bar();

finally providing me with just one unique instance of global sharedVariable for both A an B? In this last case does it matter if C is .lib or .dll?


Solution

  • Does it mean that in this scenario I will have multiple copies of sharedVariable within A and B, if I call getShared() in each of them?

    Yes: this is one area where Windows DLLs greatly differ from UNIX shared libraries. A DLL is pretty much self contained and getShared() in A "knows nothing" about anything in B.

    If C is also a .dll then would be the situation same, or as C is dll I have just one unique instance of that sharedVariable for both A and B?

    The latter. Calls from A or B will resolve to getShared() defined in C and will return the same address of sharedVariable contained within C.DLL.