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?
Yes, you have to make A a shared DLL, or else define it as extern in B and C and link all three statically.
No - they are not shared.
From Richter's 'Windows via C/C++' (p583):
When one process maps a DLL image file into its address space space, the system creates instances of the global and static data variable as well.
So, if you need to share a resource between multiple executables you will need to create a shared kernel object of some sort. I would suggest creating a named file mapping, which you can then use to read and write to from the separate processes (with appropriate Mutex exclusion, of course.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With