General global variable in C ++ static library

I have an MS C ++ project (let him ask Project A), which I am compiling now as a static library (.lib). It defines the global variable foo. I have two other projects that compile separately (name them B and C, respectively), and each links a common static library A. Both B and C are dlls that end up loading into the same process. I would like to share one instance of foo from A between B and C in the same process: singleton. I am not sure how to execute a single template here with project A, since it is statically compiled into B and C separately. If I declare foo to be extern in both B and C, I get different instances in B and C. Using the standard simple singleton method template with the static getInstance method results in two static foo instances.

Is there a way to do this while project A is statically compiling in B and C? Or do I need to make a dll?

+5
source share
3 answers

Yes, you must make A a common DLL, or define it as extern in B and C and link all three statically.

+4
source

No - they are not used.

From Richter 'Windows via C / C ++' (p583):

When one process maps a DLL image file to its address system, it creates instances of a global and static data variable.

, , - . , ( Mutex, .)

+2

:

A.EXE, B.LIB. C.DLL, B.LIB.

, B.LIB

, , A.exe C.DLL. A.EXE C.DLL B.LIB

, , B.LIB "fantom", C.DLL, A.exe?

, . . Linux , . -fPic GCC. .

/ , B.LIB A.EXE C.DLL, /. A.EXE C.DLL / B.LIB, A.EXE.

, C.DLL / B.LIB, A.EXE C.DLL , B.LIB A.EXE.

B.LIB, C.DLL, - B.LIB A.EXE C.DLL

To reduce global bloat, you should split your A.LIB more than D.DLL, E.DLL, which are loaded by A.EXE and passed through the interface to your C.DLL

To reduce bloated code to zero, you should use the full independent interface method.

0
source

All Articles