tags:

views:

386

answers:

4

Normally using a variable in a .cpp file results in the variable being globally available, like this:

.h file:
extern int myGlobal;
void work();

.cpp file:
int myGlobal = 42;
void work(){ myGlobal++; }

When the .cpp file is put in a static library and more than one shared library (DLL) or executable links against the static library, each one has its own copy of myGlobal. work() would modify its own version of the variable.

My question now: is there a way to get a process-wide unique variable or pointer to that variable? Similar what thread-local storage would be for thread-wide variables. It doesn't have to be platform independent. Bonus points if it works in Win32 :)

+4  A: 

Simple: make all the DLLs in the process link to a single DLL that exposes the variable.

Daniel Earwicker
+3  A: 

Either don't statically link to it (stick myGlobal in a DLL), or only link against the static library once (potentially more of a pain in the neck to achieve).

Logan Capaldo
A: 

I suggest you have a look at Boost.Interprocess, in particular this page on sharing memory between multiple processes. There you can find how to use this library to create a shared memory space, open one that's already created (actually "open or create"), resize it to your needs and access it. There's a simple example that should get you going quite fast.

Benoît
Question says "process-wide", not multiple process. Shared memory within the same process is probably a little bit overkill.
Logan Capaldo
You're right. But it does work and it's not that difficult to use. So why not ? :)
Benoît
Beware: boost::interprocess is full of pitfalls and gotchas. For example, on some platforms it has a tendency to busy-wait in things like wait conditions. Make sure you read the boost code you're using.
jeffamaphone
I did look at Boost.Interprocess, but since I only need it process-wide, I think the easy solution would be to put the variable in a separate dll. Thanks for the suggestion, though!
vividos
A: 

Perhaps this is overkill for a single process, but I've used shared sections to achieve something similar to what you describe.

Ismael
Since I only need a process-wide variable, shared sections would be too much. Thanks for the suggestion, though!
vividos