Roberto
Roberto

Reputation: 713

Access the same namespace from different libraries

I build several libraries (static and dynamic ones) which all need to access a namespace containing namespace-global variables.

The functions for altering the variables are defined in one cpp file. If a function inside a library accesses one of those functions, it seems to create a local copy of the whole cpp file, including all variables (and maybe also functions). This means, every library accesses a variable at a different address, resultig in a mess, because the variables have to be shared by all libraries. How can I get around this?

The sourcecode, reduced to the essential:

//include.h
namespace myns {
    extern int vars;
}

.

//include.cpp
#include <myns/include.h>
namespace myns {
    int vars;
    void MyClass::setVars(int var) {
        vars = var;
    }
}

.

//myclass.h
namespace myns {
    class MyClass {
        void setVars(int var);
    }
}

.

//myclass.cpp.in
//This will be generated by CMake and then compiled into a library
#include <myns/@package@/myclass.h>
namespace myns {
    namespace @package@ {
        class __declspec(dllexport) MySubclass : public MyClass {
            MySubclass();
        }
        MySubclass::MySubclass() {
            setVar(@value@);
        }
    }
}
using namespace myns;
extern "C" __declspec(dllexport) void exported_function() {
    new MySubclass();
}

Everytime the exported_function() is called, the vars variable would have a different address. Why does that happen? I need all library functions to access the same vars variable!

Upvotes: 0

Views: 958

Answers (1)

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

Reputation: 145419

Even though the language bears little resemblance to the alleged "C++", and even though the question is severely underspecified (what kind of libraries?), the problem is sufficiently well known that it's answerable.

In short, each Windows DLL has its own internal variables etc. (a Windows DLL is more akin to an executable than to a C++ library).

Note that standard C++ does not support dynamically loaded libraries except for a single cryptic little statement about global initialization order.

A solution is to put the shared state in its own DLL.


By the way, when you are providing setters and getters for a variable there is really little point in also making it directly accessible. That's asking for trouble. But then, using a global variable is, in the first place, also asking for trouble.

Upvotes: 1

Related Questions