[英]Segmentation fault and undefined reference to `dlopen'
我嘗試在C ++中動態加載庫。 我遵循本教程。 我的文件夾結構是這樣的:
├── 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
,效果很好,但是當我嘗試使用g++ -ldl main.cpp -o test
編譯我的main時,出現此錯誤:
/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我通過使用此命令來編譯我的主要解決了問題。 g++ main.cpp -ldl -o test
在此答案中找到此修復程序。
但是現在當我嘗試運行./test
時,出現了Segmentation fault
。 似乎在這一行tst->init();
但是指針看起來有效。
編輯2按照本教程,我會遇到相同的錯誤, Segmentation fault
。
如果您有很好的教程或文檔,它將會真正有幫助。
這與dlopen
部分無關。 您的class TestLib
缺少從TestVir
的繼承:
class TestLib : public TestVir
您還應該將create
/ destroy
簽名固定為相同類型。 由於要隱藏TestLib
類,因此應返回並使用TestVir*
。
extern "C" TestVir* create()
{
return new TestLib();
}
extern "C" void destroy(TestVir* Tl)
{
delete Tl ;
}
還要將函數類型放在標題中,否則您將在一段時間后將自己摔倒。 為此,您還必須在基類中具有虛擬析構函數。
class TestVir
{
public:
virtual void init()=0;
virtual ~TestVir() = default; // note: C++11
};
順便說一句:您的錯誤處理缺少刷新,並且在出現錯誤的情況下也不應繼續。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.