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

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

问题描述

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



什么是命令行选项来做到这一点?如果我指定-static,那么gcc将拒绝动态链接任何库。

解决方案

静态链接任何系统库,特别是针对 libc ,在现代UNIX或Linux系统上,二进制文件显着减少了 em便携性。 然而,使用向后兼容性(旧系统上链接的二进制文件继续在所有新文件系统上运行)对您有利,可以通过链接在旧系统上使用二进制文件(我使用RedHat 6.2,而且我还没有看到过去八年里我的二进制文件不能运行的Linux系统),或者使用类似于

回答您的原始问题:

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

将导致链接器使用libfoo的归档版本。 [在 -Wl,-Bdynamic 后面加上尾部是很重要的,这样你就不会强制使用静态libc。]


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.

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

解决方案

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.

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.

To answer your original question:

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

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天全站免登陆