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
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
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)
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:
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.