proteneer
proteneer

Reputation: 592

Multiple copies of static members when mixing shared/static libs

Situation:

I have:

class Platform {

public:
   Platform() { count++; cout << getCount();}
   static int getCount() { return count; }

private:
   static int count;

}

which is created as static library.

Consider making a dynamic library extension

class __declspec(dllimport/dllexport) DerivedPlatform : public Platform {

}

And yes I am aware that I'm deriving from a non-dll interface class.

Per: Are static fields inherited?, there should only be a single instance of count ever.

Here's the tricky part, I actually end up with two different copies of count (even though count is declared static). Ie, upon loading in the dll and calling registerPlatforms(), it increments a DIFFERENT count object:

int main() {

   Platform::count = 0;
   Platform A; // increases count by 1, cout shows 1

   loadPlugin(); // loads the shared library DerivedPlatform
   DerivedPlatform D; // increases count by 1 again, cout shows 2

   cout << Platform::getCount(); // shows 1 !!!!!!

}

I have no idea how to resolve this, ie. how to ensure that only one static variable persists. Apparently DLLs have their own heap for static variables - so it sort of makes sense why this would happen.

Upvotes: 4

Views: 1144

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308158

Yes, that's what happens when you link a static library into both an executable and a DLL. Neither has any knowledge of the other at link time so they both get a copy. For the code itself that usually doesn't hurt anything, but for static variables it can be a real hassle.

You need to rearchitect your solution so that the static library is in a DLL instead, either the existing one or a brand new third one. Or eliminate all static variables.

Upvotes: 4

Related Questions