不能 link 包含 iostream 的动态库

Can't link a dynamic lib including iostream

ld 行为异常,我想了解发生了什么。在 mycode.cpp 中,我有以下内容:

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

// awesome stuff here

我用 g++ -fPIC -c mycode.cpp 编译它,link 用 ld -Bshareable -o libmylib.so mycode.o 编译它。很有魅力。

那我想在mycode.cpp中调用cout。实际上,即使在添加这个 cout 之前,如果我只是在上面的代码中添加 #include <iostream>,而 linking 我得到错误

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

如果我 link 它与 g++ -shared,它可以工作,但这不是重点。我不明白这里出了什么问题,我正在寻找见解。

编辑:我知道必须直接调用 g++ 而不是 ld。我的问题是,我想了解引擎盖下的内容:为什么在算法已经存在的情况下包含 iostream 会破坏事物(所以 ld 知道 stdc++)

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

它只是偶然

用户级代码应该从不 link直接用ld编辑,并且应该总是使用适当的编译器驱动程序(此处为 g++)来执行 link。其他任何事情,你都会因奇怪的 link 时间或运行时错误而失败(就像你在这里所做的那样)。