分段错误和对“dlopen”的未定义引用

Segmentation fault and undefined reference to `dlopen'

我尝试在 C++ 中动态加载库。我遵循 this 教程。 我的文件夹结构是这样的:

├── main.cpp
├── testLib.cpp
├── testLib.h
├── testLib.so
└── testVir.h

main.cpp

#include<iostream>
#include<dlfcn.h>
#include<stdio.h>
#include "testVir.h"

using namespace std;

int main()
{
    void *handle;
    handle = dlopen("./testLib.so", RTLD_NOW);
    if (!handle)
    {
           printf("The error is %s", dlerror());
    }

    typedef TestVir* create_t();
    typedef void destroy_t(TestVir*);

    create_t* creat=(create_t*)dlsym(handle,"create");
    destroy_t* destroy=(destroy_t*)dlsym(handle,"destroy");
    if (!creat)
    {
           cout<<"The error is %s"<<dlerror();
    }
    if (!destroy)
    {
           cout<<"The error is %s"<<dlerror();
    }
    TestVir* tst = creat();
    tst->init();
    destroy(tst);
    return 0 ;
}

testLib.cpp

#include <iostream>
#include "testVir.h"
#include "testLib.h"

using namespace std;
void TestLib::init()
{
   cout<<"TestLib::init: Hello World!! "<<endl ;
}

//Define functions with C symbols (create/destroy TestLib instance).
extern "C" TestLib* create()
{
    return new TestLib;
}
extern "C" void destroy(TestLib* Tl)
{
   delete Tl ;
}

testLib.h

#ifndef TESTLIB_H
#define TESTLIB_H

class TestLib
{
 public:
     void init();
};

#endif

testVir.h

#ifndef TESTVIR_H
#define TESTVIR_H

class TestVir
{
public:
  virtual void init()=0;
};

#endif

我使用这个命令得到了我的 testLib.so g++ -shared -fPIC testLib.cpp -o testLib.so , 这工作正常,但是当我尝试编译我的 main 时 g++ -ldl main.cpp -o test 我收到这个错误:

/tmp/ccFoBr2X.o: In function `main':
main.cpp:(.text+0x14): undefined reference to `dlopen'
main.cpp:(.text+0x24): undefined reference to `dlerror'
main.cpp:(.text+0x47): undefined reference to `dlsym'
main.cpp:(.text+0x5c): undefined reference to `dlsym'
main.cpp:(.text+0x6c): undefined reference to `dlerror'
main.cpp:(.text+0x95): undefined reference to `dlerror'
collect2: error: ld returned 1 exit status

G++ 版本(来自 g++ --version):
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4

我不知道发生了什么,我需要一些资源来了解它是如何工作的。

编辑 1 我通过使用此命令编译我的 main.c 解决了这个问题。 g++ main.cpp -ldl -o test。在此 answer 中找到此修复程序。

但现在当我尝试 运行 ./test 我得到 Segmentation fault。而且似乎 位于这一行 tst->init(); 但指针看起来有效。

编辑 2 按照 this 教程,我得到了同样的错误,Segmentation fault

如果您有很好的教程或文档,那将会很有帮助。

这与dlopen部分无关。您的 class TestLib 缺少来自 TestVir 的继承:

class TestLib : public TestVir

您还应该将 create/destroy 签名修复为同一类型。既然你想隐藏 TestLib class,你应该 return 并取 TestVir*.

extern "C" TestVir* create()
{
    return new TestLib();
}
extern "C" void destroy(TestVir* Tl)
{
   delete Tl ;
}

还要把函数类型写成header,不然过会儿搬起石头砸自己的脚。为此,您还必须 have virtual destructor in the base class.

class TestVir
{
public:
    virtual void init()=0;
    virtual ~TestVir() = default; // note: C++11
};

顺便说一句:您的错误处理缺少刷新,如果出现错误,您不应该继续。