gpt4 book ai didi

c++ - 动态库的链接问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:23:27 26 4
gpt4 key购买 nike

我正在尝试动态加载实现基类的库,该基类定义在另一个库中。我已按照此处描述的说明进行操作:

http://www.linuxjournal.com/article/3687?page=0,1

我创建了一个 shape 类并将它放在一个单独的库中(不是真正的库,因为它只是一个头文件,但这样说),我还创建了两个动态库,圆形和方形,它们继承自形状和实现 draw 方法并在 factory map 中注册它们的 maker 函数。让我向您展示代码:

形状.h:

#ifndef __SHAPE_H
#define __SHAPE_H
#include <map>
#include <string>

// base class for all shapes
class shape{
public:
// our global factory
virtual void draw()=0;
};

// typedef to make it easier to set up our factory
typedef shape *maker_t();
extern std::map<std::string, maker_t *, std::less<std::string> > factory;


#endif // __SHAPE_H

圆.h

#ifndef __CIRCLE_H
#define __CIRCLE_H

#include "shape.h"

class circle : public shape
{
public:
void draw();
};
#endif // __CIRCLE_H

圆.cpp:

#include <iostream>
#include "circle.h"

void circle::draw()
{
// simple ascii square
std::cout << "\n";
std::cout << " ****\n";
std::cout << " * *\n";
std::cout << " * *\n";
std::cout << " * *\n";
std::cout << " * *\n";
std::cout << " * *\n";
std::cout << " ****\n";
std::cout << "\n";
}

extern "C"
{
shape *maker()
{
return new circle;
}
class proxy
{
public:
proxy()
{
// register the maker with the factory
factory["circle"] = maker;
}
};
// our one instance of the proxy
proxy circle_p;
}

我不会讨论正方形,因为它几乎与圆圈相同,既不是动态加载库的实际“客户端”,因为它确实有效。

现在我的问题是,如果你在 circle.so 中有其他类和功能(这是我的情况),并且在某些情况下你需要在编译时链接(-l 选项),我会遇到问题。我创建了一个测试客户端库,它不是动态加载圆圈,而是在编译时执行。链接器失败并输出以下内容:

Invoking: GCC C++ Linker
g++ -rdynamic -L/home/lizardking/workspace/dynclientest/Debug/libs -o "test2" ./src/test2.o -ldynlib_circle
/home/lizardking/workspace/dynclientest/Debug/libs/libdynlib_circle.so: undefined reference to `factory'
collect2: ld returned 1 exit status

这个测试应用程序的 main.cpp 只是一个 hello world!:

#include <iostream>
using namespace std;

int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}

我真的不知道为什么链接器总是提示 map ......有什么想法吗???

谢谢!

最佳答案

您只在 shape.h 中将 factory 声明为 extern。

你应该放这样的东西:

std::map<std::string, maker_t *, std::less<std::string> > factory;

进入 shape.cpp 以在 shape.o 中保留空间(即创建定义的符号)。

关于c++ - 动态库的链接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5870209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com