1

ld is acting weirdly and I want to understand what's going on. In a mycode.cpp, I have the following:

#include <algorithm>
#include "mycode.hpp"

// awesome stuff here

I compile it with g++ -fPIC -c mycode.cpp and link it with ld -Bshareable -o libmylib.so mycode.o. Works like a charm.

Then I want to call cout in mycode.cpp. Actually, even before adding this cout, if I just add #include <iostream> in the code above, while linking I get the error

mycode.o: In function `__static_initialization_and_destruction_0(int, int)':
mycode.cpp:(.text+0x50): undefined reference to `__dso_handle'
ld: mycode.o: relocation R_X86_64_PC32 against undefined hidden symbol `__dso_handle' can not be used when making a shared object
ld: final link failed: Bad value

If I link it with g++ -shared, it works, but that's not the point. I do not understand what's wrong here, and I am looking for insights.

EDIT: I understand one must call g++ instead of ld directly. My problem is, I want to understand what's under the hood: why including iostream break things while algorithm is already here (so ld knows stdc++)

Florian Richoux
  • 1,543
  • 1
  • 14
  • 28
  • 2
    pretty sure your answer is right there: [Using only g++ works, but not “g++ -c” and ld](http://stackoverflow.com/questions/6704780/using-only-g-works-but-not-g-c-and-ld) – Dart Feld Nov 18 '16 at 18:26
  • 1
    See http://www.linuxquestions.org/questions/programming-9/fyi-shared-libs-and-iostream-c-331113/page2.html#post2936978 but take into account that it is for a very old version of gcc – Leon Nov 18 '16 at 19:04
  • Don't call ld directly. Link with GCC. – rubenvb Nov 18 '16 at 19:12

1 Answers1

2

link it with ld -Bshareable -o libmylib.so mycode.o. Works like a charm.

It only works by accident.

User-level code should never be linked directly with ld, and should always use the appropriate compiler driver (g++ here) to perform the link. Anything else, and you'll fail with weird link-time or runtime errors (just as you did here).

Employed Russian
  • 199,314
  • 34
  • 295
  • 362