无法链接到共享库 [英] Cannot link to shared library

查看:101
本文介绍了无法链接到共享库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to compile a minimal shared library and link to it and have been failing for two hours now. Here is ALL the code:

// 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;
}

这是我尝试编译的方式:

And this is how I try to compile it:

$ 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类已根据我的判断正确导出:

The library compiles just fine and the Rect class is properly exported from what I can tell:

$ 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) )

The strangest thing is that this compiles fine and works on my work computer (Kubuntu 12.10 64bit) but fails to link properly on any other machine I've tried (4 in total, all 64-bit Ubuntu/Kubuntu 12.04 and 12.10)

我竭尽所能.将详细选项传递给链接器表明,librect.so确实已成功找到.

I tried everything I could think of. Passing the verbose option to the linker shows that the librect.so is indeed found successfully.

有人知道可能是什么问题吗?

Does anybody have a clue what the problem might be?

推荐答案

库必须在本地翻译单位后

The libraries have to go after the local translation units:

g++ -L. -Wl,-rpath,'.' client.cpp -o client -lrect
#                                           ^^^^^^

与链接器查找未解析符号的方式有关;如果您感到好奇,请在互联网上搜索有关此方面的大量信息.

It has to do with how unresolved symbols are looked up by the linker; search the internet for a plethora of information on this if you're curious.

这篇关于无法链接到共享库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆