使用静态单例类实例会导致动态加载失败

时间:2020-01-09 03:44:43

标签: c++ singleton shared-libraries poco-libraries dynamic-loading

我正在制作一个共享库,该库导出使用静态类实例的函数。共享库旨在动态加载。但是,由于某些原因,使用静态类实例会导致动态加载失败。我正在使用Poco加载图书馆。

//my_library.h
#ifndef MY_LIB_H
#define MY_LIB_H

#define DUMMY_MSG 1;

class SendClass
{
  public:
    SendClass() = default;
    SendClass( const SendClass &other ) = delete;
    SendClass &operator=( const SendClass &other ) = delete;

    static SendClass *get_instance(){ return &singleton_instance; };

    int send(){ return DUMMY_MSG; };

  private:
    static SendClass singleton_instance;
};

extern "C" __attribute__ ((visibility ("default"))) int send();//this is the function to be exported

inline int send()
{
  return SendClass::get_instance()->send();
}

#endif // MY_LIB_H

我使用以下命令将上述头文件编译为共享库,并将该库放在/ tmp /

g++ -shared -fPIC -o libexp.so my_library.h

然后我尝试在主程序中加载库

//main.cpp
#include "Poco/SharedLibrary.h"

using namespace std;

typedef int(*SENDFUNC)();

int main
(
  int argc,
  char **argv
)
{
    Poco::SharedLibrary lib;
    lib.load( "/tmp/libexp.so" );    //crashes here!
    SENDFUNC send_func = (SENDFUNC)lib.getSymbol("send");
    int msg = send_func();
    return 0;
}

程序在“ lib.load(“ /tmp/libexp.so”);”行崩溃。并显示以下消息:

抛出
实例后调用

terminate 'Poco :: LibraryLoadException'what():无法加载库

但是,如果将SendClass :: get_instance的主体更改为以下内容,则动态加载成功完成

//if SendClass::get_instance is implemented as follows, dynamic loading succeeds    
static SendClass *get_instance(){ return new SendClass; };

那为什么使用静态实例会导致动态加载失败?

1 个答案:

答案 0 :(得分:0)

按照@ ALX23z的建议,我通过添加以下cpp文件解决了该问题

//my_library.cpp
#include "my_library.h"

SendClass SendClass::singleton_instance;
相关问题