4

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So how come if I change the static library into a .dll, it then works? Do ALL .dlls share the same heap?
@proteneer, it has nothing to do with the heap - static variables are stored in a separate location near the code. Putting it into a DLL just ensures that only one copy exists.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.