Zach Zach - 1 month ago 15
C++ Question

Shared global variable in C++ static library

I have a MS C++ project (let's call it project A) that I am currently compiling as a static library (.lib). It defines a global variable foo. I have two other projects which compile separately (call them B and C, respectively) and each links the shared static library A in. Both B and C are dll's that end up loaded in the same process. I would like to share a single instance of foo from A between B and C in the same process: a singleton. I'm not sure how to accomplish the singleton pattern here with project A since it is statically compiled into B and C separately. If I declare foo as extern in both B and C, I end up with different instances in B and C. Using a standard, simple singleton class pattern with a static getInstance method results in two static foo instantiations.

Is there any way to accomplish this while project A is statically compiled into B and C? Or do I have to make A a DLL?

Answer

Yes, you have to make A a shared DLL, or else define it as extern in B and C and link all three statically.