如何更改默认的 rustc/Cargo 链接器? [英] How do I change the default rustc / Cargo linker?
问题描述
我想让 rustc 在特定的 crate 中使用 lld
作为链接器而不是 ld
.所以我在我的项目目录中创建了 .cargo/config
,内容如下:
I would like to make rustc use lld
as a linker instead of ld
in a particular crate. So I create .cargo/config
in my project directory with the following:
[target.x86_64-unknown-linux-gnu]
linker = "ld.lld"
导致链接器错误的原因:
Which leads to linker errors:
$ cargo build
...
= note: ld.lld: error: unable to find library -ldl
ld.lld: error: unable to find library -lrt
ld.lld: error: unable to find library -lpthread
ld.lld: error: unable to find library -lgcc_s
ld.lld: error: unable to find library -lc
ld.lld: error: unable to find library -lm
ld.lld: error: unable to find library -lrt
ld.lld: error: unable to find library -lpthread
ld.lld: error: unable to find library -lutil
ld.lld: error: unable to find library -lutil
与 rust-lld
相同.如果我设置 linker = "ld"
(这应该是默认值,对吧?),我就得到
Same thing with rust-lld
. If I set linker = "ld"
(which should be the default, right?), I just get
= note: ld: cannot find -lgcc_s
我尝试手动解决所有丢失的库(使用 -C link-arg=--library-path=/usr/lib/x86_64-linux-gnu
等),但它只会导致错误的链接和段错误的二进制文件.
I tried to resolve all the missing libraries manually (with -C link-arg=--library-path=/usr/lib/x86_64-linux-gnu
and the like), but it only lead to wrong linkage and a segfaulting binary.
有趣的是,如果我将 /usr/bin/ld
替换为 /usr/bin/ld.lld
的符号链接,它运行良好(没有错误,并且从编译后的二进制文件中我看到它确实与 lld
链接).但是,我不想让 lld
成为我的系统范围的链接器,我只想在特定的 Rust crate 中使用它.
Interestingly enough, if I replace /usr/bin/ld
with a symlink to /usr/bin/ld.lld
, it works great (no errors, and from the compiled binary I see that it was indeed linked with lld
). However, I don't want to make lld
my system-wide linker, I just want to use it in a particular Rust crate.
那么更改默认 rustc 链接器的正确方法是什么?
So what is the proper way to change the default rustc linker?
推荐答案
感谢@Jmb 的评论,我找到了解决方案.事实证明,rustc
使用的默认链接器实际上是 cc
(这是有道理的 - 它提供了编译/链接 C 代码所需的所有默认值,这也适用于 Rust).我们可以向 cc
传递一个参数,使其与 lld
链接:
Thanks to @Jmb comment, I found a solution. Turns out that the default linker that rustc
uses is actually cc
(which makes sense - it supplies all the needed defaults to compile/link C code, which also work for Rust). We can pass an argument to cc
to make it link with lld
:
[target.x86_64-unknown-linux-gnu]
rustflags = [
"-C", "link-arg=-fuse-ld=lld",
]
现在 cargo build
与 lld
链接.
这篇关于如何更改默认的 rustc/Cargo 链接器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!