【发布时间】:2017-01-23 00:55:21
【问题描述】:
我浏览了多个堆栈溢出帖子并尝试实现以下示例,该示例使用 dlopen 和 c++ 对象类 我有以下代码。
1) 文件 hello.cc
#include <stdio.h>
#include "hello.h"
A::A() {
init1();
}
void A::init1() {
printf("\n init ");
}
2) 文件 hello.h
#include <iostream>
class A {
public:
A();
void init1();
inline void fun () { cout << "\n Inside fun"; }
};
extern "C" A* createA() {
return new A;
}
}
3) 文件 main.cpp
#include<iostream>
#include<dlfcn.h>
#include "hello.h"
using namespace std;
int main() {
void *handle;
handle = dlopen("./libhello.so", RTLD_LAZY | RTLD_GLOBAL);
if (!handle) {
cout << "The error is " << dlerror();
}
return 0 ;
}
我正在使用以下步骤来创建共享库
1) g++ -g -fPIC -c hello.cc
2) g++ -g -shared -o libhello.so hello.o
3) g++ -g -o myprog main.cpp -
main.cpp:(.text+0x18): undefined reference to `A::A()' . The function createA in hello.h is declared so the same can be used to dlsym
- 我无法在 dlsym 中使用 createA
- 即使我不使用 dlsym,我也会收到对 `A::A() 的未定义引用
- 我的查询是正确的是在 dlsym 中使用 C++ 类对象
- 来自 dlopen 的人我无法推断 RTLD_LAZY RTLD_GLOBAL RTLD_NOW 标志的意义
【问题讨论】:
-
C 不能处理类。
-
extern "C" A* createA()明确表示不是。 -
@πάντα ῥεῖ 这意味着别的东西。阅读:en.wikipedia.org/wiki/Name_mangling
标签: c++ gcc linker shared-libraries dlopen