在 gcc 中同时使用静态和动态链接库 [英] Use both static and dynamically linked libraries in gcc

查看:45
本文介绍了在 gcc 中同时使用静态和动态链接库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要分发一个可以在尽可能多的 x86 Linux 发行版上运行的二进制文件.这意味着我必须静态链接一些库,比如 glibc,因为用户可能没有我使用的版本.其他库必须动态链接,例如 fontconfig,因为它依赖于缓存文件格式和硬编码位置,每个系统可能会有所不同.

I need to distribute a binary that will run on as many x86 Linux distributions as possible. That means that I have to statically link some libraries, like glibc, because the user might not have the version I use. Other libraries have to be dynamically linked, like fontconfig, because it relies on a cache file format and hard coded locations that may differ on each system.

执行此操作的命令行选项是什么?如果我指定 -static,那么 gcc 将完全拒绝动态链接任何库.

What are the command line options to do this? If I specify -static, then gcc will refuse to dynamically link any libraries at all.

推荐答案

在现代 UNIX 或 Linux 系统上静态链接任何系统库,尤其是 libc 使二进制文件显着减少 便携.只是不要这样做.

Statically linking against any system library, and especially against libc, on modern UNIX or Linux systems makes the binary significantly less portable. Just don't do it.

相反,使用向后兼容性(链接在旧系统上的二进制文件继续在所有新系统上运行)对您有利,或者通过链接旧系统上的二进制文件(我使用 RedHat 6.2,我还没有看到 Linux 系统)我的二进制文件在过去 8 年内不会运行),或者使用类似 autopackage(在写完这个答案后已被删除).

Instead, use backward compatibility (binaries linked on an older system continue to run on all newer ones) to your advantage, either by linking your binary on an old system (I use RedHat 6.2, and I have not seen a Linux system where my binary will not run in the last 8 years), or by using something like autopackage (which has been deleted after this answer was written).

回答您最初的问题:

gcc main.o -Wl,-Bstatic -lfoo -Wl,-Bdynamic

将导致链接器使用 libfoo 的存档版本.[准确地使用尾随的 -Wl,-Bdynamic 很重要,这样您就不会强制使用静态 libc.]

will cause linker to use archive version of libfoo. [It is important to have the trailing -Wl,-Bdynamic precisely so you don't force static libc.]

这篇关于在 gcc 中同时使用静态和动态链接库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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