Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 633
Zach Avatar asked Jul 06 '10 14:07

Zach


2 Answers

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

like image 144
Jeremy Bell Avatar answered Sep 22 '22 06:09

Jeremy Bell


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.)

like image 43
Ragster Avatar answered Sep 24 '22 06:09

Ragster