Static members of static libraries

一个人想着一个人 提交于 2019-12-05 02:00:06

问题


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.



来源:https://stackoverflow.com/questions/10561845/static-members-of-static-libraries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!