我正在尝试编译一个最小的共享库并链接到它,现在已经失败了两个小时。这是所有代码:
// 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 64bit)上正常工作,但无法在我尝试过的任何其他机器上正确链接(总共 4 个,所有 64 位 Ubuntu/Kubuntu 12.04 和 12.10)
我尝试了我能想到的一切。将详细选项传递给链接器表明确实成功找到了 librect.so。
有人知道问题可能是什么吗?