无法链接到共享库
Cannot link to shared library
我正在尝试编译一个最小的共享库并链接到它,现在已经失败了两个小时。这是所有代码:
// rect.h
class Rect{
private:
int width_, height_;
public:
Rect(int width, int height);
int width();
int height();
};
// rect.cpp
#include "rect.h"
Rect::Rect(int width, int height)
:width_(width), height_(height){}
int Rect::width() { return width_; }
int Rect::height() { return height_; }
// client.cpp
#include "rect.h"
#include <iostream>
int main() {
std::cout << Rect(1,2).width();
return 0;
}
这就是我尝试编译它的方式:
$ g++ -shared -o librect.so rect.cpp
$ g++ -L. -lrect -Wl,-rpath,'.' client.cpp -o client
/tmp/cc0Xe7ms.o: In function `main':
client.cpp:(.text+0x1a): undefined reference to `Rect::Rect(int, int)'
client.cpp:(.text+0x26): undefined reference to `Rect::width()'
collect2: error: ld returned 1 exit status
该库编译得很好,并且 Rect 类已从我能说的内容中正确导出:
$ nm -D librect.so
0000000000201028 B __bss_start
w __cxa_finalize
0000000000201028 D _edata
0000000000201030 B _end
0000000000000738 T _fini
w __gmon_start__
00000000000005b8 T _init
w _ITM_deregisterTMCloneTable
w _ITM_registerTMCloneTable
w _Jv_RegisterClasses
0000000000000714 T _ZN4Rect5widthEv
0000000000000724 T _ZN4Rect6heightEv
00000000000006f0 T _ZN4RectC1Eii
00000000000006f0 T _ZN4RectC2Eii
最奇怪的是,这编译得很好并且可以在我的工作计算机(Kubuntu 12.10 64位)上运行,但无法在我尝试过的任何其他机器上正确链接(总共 4 个,所有 64 位 Ubuntu/Kubuntu 12.04 和 12.10)
我尝试了我能想到的一切。将详细选项传递给链接器表明确实成功找到了 librect.so。
有人知道问题可能是什么吗?
图书馆必须遵循本地翻译单元:
g++ -L. -Wl,-rpath,'.' client.cpp -o client -lrect
# ^^^^^^
这与链接器如何查找未解析的符号有关;如果你好奇,可以在互联网上搜索大量信息。
相关文章:
- 无法在Ubuntu上将共享库与Eclipse链接
- CMake - 更改共享库链接选项
- 与共享库链接时未定义的引用
- 如何在 Linux 中构建共享库时使未定义引用的链接器失败
- 共享对象、符号、C/C++ 库链接和加载
- 如果同时存在共享库和动态库,则链接器将首选哪个库?
- 如何防止 CMake 在构建时(而不是在安装时)为共享库创建符号链接?
- c++ 链接器错误"针对'.rodata.str1.1'的重新定位R_X86_64_32"链接 CXX 共享库 libsrt.so
- 停止共享库链接丢弃未使用的类
- 链接二进制库或共享库时,为什么必须传入我依赖的共享库?
- 使用共享库编译可执行文件时仅链接所需的符号
- C++ 为什么要级联共享对象链接
- 与 32 位共享对象的链接问题
- 使用 pybind11 构建库,链接其他共享库
- 运行程序时找不到共享对象库,但在编译过程中链接了它
- 链接共享库依赖项未在 ldd 中列出
- 将共享对象与静态库链接
- CMake:修改共享库时的冗余链接
- 与MinGW的静态和动态/共享链接
- Qt-多个QtableWidget可以共享链接的项目