独立的共享库 [英] Self-contained shared library

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

问题描述

我需要创建一个共享库,必须将其自己的依赖项(包括libc / libstdc ++)静态链接到该共享库,以生成自包含的二进制文件。我试图这样做

I need to create a shared library whose own dependencies including libc/libstdc++ have to be statically linked to it to produce a self-contained binary. I tried to do this

g++ -c -fpic -o foo.o foo.cpp
g++ -static -shared -o foo.so foo.o

失败,显示:

/usr/bin/ld.bfd.real: /usr/local/lib/gcc/x86_64-unknown-linux-gnu/5.2.0/crtbeginT.o: relocation R_X86_64_32 against `__TMC_END__' can not be      used when making a shared object; recompile with -fPIC
/usr/local/lib/gcc/x86_64-unknown-linux-gnu/5.2.0/crtbeginT.o: could not read symbols: Bad value
collect2: error: ld returned 1 exit status

有人可以告诉我我做错了吗?

Can somebody tell me what I am doing wrong?

推荐答案

您可以使用 -static-libstdc ++ 选项链接 libstdc ++ 静态。您可能不应该静态链接到 libc (或 libgcc ,可以将其静态链接到 -static-libgcc )(如果要创建动态库);您将要选择加载共享库的应用程序的libc版本。

You can use the -static-libstdc++ option to link libstdc++ statically. You probably shouldn't link statically to libc (or libgcc, which you can link statically with -static-libgcc should you need to) if you're making a dynamic library; you'll want to pick up the libc version of the application that loads your shared library.

控制静态链接的其他选项可以在 GCC手册。您也可以通过将参数传递给链接器( -Wl,< argument> 或调用 ld 直接)。 LD手册列出了允许的选项。

Other options controlling static linking can be found in the GCC manual. You may also be able to achieve the desired results by passing arguments to the linker (-Wl,<argument>, or calling ld directly). The LD manual lists the permitted options.

示例:

我编写了以下代码

#include <iostream>

extern "C" void do_something() {
    std::cout << "Doing something!\n";
}

并将其编译为 .o 文件如下:

and compiled it to a .o file as follows:

g++ -fPIC -c -o tmp.o tmp.cpp

然后我从中产生了两个共享库。一个带有-static-libstdc ++,另一个没有:

I then produced two shared libraries from it. One with -static-libstdc++, and one without:

g++ -shared -o tmp-shared.so tmp.o
g++ -shared -static-libstdc++ -o tmp-static.so tmp.o

进行比较, ldd tmp-shared.so

linux-vdso.so.1 =>  (0x00007fffc6dfd000)
libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00002b708cb43000)
libm.so.6 => /lib64/libm.so.6 (0x00002b708ce4c000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00002b708d0cf000)
libc.so.6 => /lib64/libc.so.6 (0x00002b708d2dd000)
/lib64/ld-linux-x86-64.so.2 (0x00000035c6c00000)

ldd tmp-static.so

linux-vdso.so.1 =>  (0x00007fff99bfd000)
libm.so.6 => /lib64/libm.so.6 (0x00002acbec030000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00002acbec2b3000)
libc.so.6 => /lib64/libc.so.6 (0x00002acbec4c1000)
/lib64/ld-linux-x86-64.so.2 (0x00000035c6c00000)

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

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