无法链接到共享库

Cannot link to shared library

本文关键字:共享 链接      更新时间:2023-10-16

我正在尝试编译一个最小的共享库并链接到它,现在已经失败了两个小时。这是所有代码:

// 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
#                                           ^^^^^^

这与链接器如何查找未解析的符号有关;如果你好奇,可以在互联网上搜索大量信息。