我现在有点困惑。昨天我有未定义的符号,即使我用g ++的-rdynamic。但是现在我没有任何错误,这更令人不安。使用共享对象中的应用程序的对象
为了解释一下我的情况,我想做一些类似于共享对象的插件。我还没有决定哪个是最好的方法。
A)我的共享对象都有一个称为寄存器的函数,它将被一个参数调用。这将是一个插件管理器。
B)我的共享对象将定义一个类,并将在加载时创建该类的实例。在该类的构造函数中,它将尝试从应用程序获取静态单例并自动注册。
据我所知,迄今为止我的第一次尝试并不是那么棒。
的main.cpp
#include "main.hpp"
#include <iostream>
#include <cstdio>
#include <dlfcn.h>
int S::shared = 0;
int main(int argc, char** argv){
std::cout << "In main -> " << S::shared << "\n";
void* triangle = dlopen("./libtwo.so", RTLD_LAZY);
if(triangle == NULL){
std::cout << "Error while loading so file\n" << dlerror() << "\n";
}
std::cout << "In main -> " << S::shared << "\n" << triangle;
return 0;
}
main.hpp
class S {
public:
static int shared;
S(){
S::shared = 0;
};
};
two.cpp
#include "main.hpp"
#include <iostream>
class MyObject {
public:
MyObject(){
std::cout << "In two -> " << S::shared << "\n";
}
};
MyObject t();
在该试样S ::共享是静态对象我想共享。对于这个简单的测试,我只使用一个int,但在未来它将是一个类的实例。
我唯一的情况A)的尝试是一个段错误...我真的不知道我错过了什么。
//结果至今(今天)
[email protected]:~/dev/WebDesign/Scproci$ scons -Q
g++ -o two.os -c -fPIC two.cpp
g++ -o libtwo.so -shared two.os
g++ -o main.o -c -fPIC main.cpp
g++ -o main -Wl,--export-dynamic main.o -ldl
[email protected]:~/dev/WebDesign/Scproci$ ./main
In main -> 0
In main -> 0
基于显示的内容,您仅显示第二种方法的代码,其行为与预期相同。 – diverscuba23
为什么不显示“在两个 - > 0”? –
未定义的符号会发生,因为S :: shared是在main.cpp中定义的,但是当链接libtwo.so时,您没有在其中定义main.o。 – Flame