Idov
Idov

Reputation: 5124

A variable across the whole application

I have a C++ windows application which is composed of several DLLs. I want to have some sort of a pool from which I'll get objects, but in a way that this pool would be available in all the DLLs.
So I put it in a "Common" dll which everbody has access to and defined it in a header file like so:
static Pool globalPool;

I do have access from every dll but this pool is created many many times.
I think it happens in each of my DLLs and in each File which include the header file with the definition.

How can I do it properly? thanks :)

Upvotes: 1

Views: 236

Answers (3)

Kristopher Johnson
Kristopher Johnson

Reputation: 82535

You'll want a header file that looks something like this:

// Common.h

#pragma once

#ifdef COMMON_BUILD
// When building Common.dll, want to export the definition of Pool
#define COMMON_EXPORT __declspec(dllexport)
#else
// When using Common.dll, want to import the definition of Pool
#define COMMON_EXPORT __declspec(dllimport)
#endif

// Declarations of shared globals
struct COMMON_EXPORT Pool {
    static int data1;
    static int data2;
};

(For more about the dllimport and dllexport stuff, see http://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx and http://msdn.microsoft.com/en-us/library/81h27t8c.aspx)

Then in your DLL's build, you will want a source file like this:

// Common.cpp

#define COMMON_BUILD
#include "Common.h"

int Pool::data1 = 0;
int Pool::data2 = 0;

Then, all the DLLs and EXEs that use it should "#include Common.h" and link with the Common DLL, and then they can use Pool::data1, etc.

Upvotes: 0

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145194

A static declaration of an object makes the object local to the compilation unit.

By using static you're creating a globalPool object (variable) in every compilation unit where you include the header.

But the way to do what you want is not to just remove the static.

Instead define a function providing access to your pool (e.g. a reference to it), and export that function or set of functions from the pool DLL.

Or better -- much better -- forget the idea. It's a generally bad idea. However, if you really want to do it, and can't see any alternative, then above is how to do it.

And if you do that, perhaps think about thread safety.

And perhaps be aware that dynamic loading of Windows DLLs does not work well with compiler support for thread local variables.

Cheers & hth.,

Upvotes: 2

Tim Kay
Tim Kay

Reputation: 11

In the header file you need

extern Pool globalPool;

Then in a .cpp file in the Common dll, you need

Pool globalPool;

The extern declaration will put it in the namespace of including modules, and the linker will resolve it to the object in the common dll.

Upvotes: 1

Related Questions