Static members of static libraries

2019-03-31 02:13发布

问题:

I have static library with static member. This library statically linked to main application and to one of its plugins. Looks like static variable initializing both in main (application) and in dll (plugin).

Question: How to avoid static variable reinitialization when dynamic library loading. Or may be I missing something simple?

More information:

This is simple static library, that contains static member and it's getter and setter:

orbhelper.h

class ORBHelper {
    static std::string sss_;
public:
    static std::string getStr();
    static void setSTR(std::string str);
};

orbhelper.cpp

std::string ORBHelper::sss_ = "init";

static std::string ORBHelper::getStr()
{
    std::cerr << "get " << sss_.c_str() << std::endl;
    return sss_;
}
static void ORBHelper::setSTR(std::string str)
{
    sss_ = str;
    std::cerr << "set " << sss_.c_str() << std::endl;
}

This library used in main.cpp and also in another dynamic library, that is loaded in main. In main.cpp I set the static string and in one of dynamic library function I want to get it.

Setting static variable in main:

main.cpp

...
ORBHelper::setStr("main");
std::cerr << ORBHelper::getStr().c_str() << std::endl; //prints 'main'
//then loading library
...

Then getting variable value in dll:

hwplugin.cpp

...
std::cerr << ORBHelper::getStr().c_str() << std::endl; //prints 'init' instead of 'main'
...

Looks like static variable has been initialized twice. First – before main.cpp, second – when dynamic library loaded. Static lib with static class linked both to main app and to dynamic lib.

P.S. too many words 'static' in my question, I know =)

回答1:

Yes, you have two instances of the helper class.

The DLL should be linked against the executable that links the static class in and use that to resolve the helper class. Do not link the DLL with the static library, but link it against the executable itself.