如何更改默认的 rustc / Cargo 链接器?

kre*_*reo 19 rust rust-cargo lld

我想让 rustclld用作链接器,而不是ld在特定的板条箱中。所以我.cargo/config在我的项目目录中创建以下内容:

[target.x86_64-unknown-linux-gnu]                                                                   
linker = "ld.lld"
Run Code Online (Sandbox Code Playgroud)

这会导致链接器错误:

$ 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
Run Code Online (Sandbox Code Playgroud)

rust-lld. 如果我设置linker = "ld"(这应该是默认值,对吧?),我就得到

  = note: ld: cannot find -lgcc_s
Run Code Online (Sandbox Code Playgroud)

我试图手动解决所有丢失的库(使用-C link-arg=--library-path=/usr/lib/x86_64-linux-gnu等),但它只会导致错误的链接和段错误的二进制文件。

有趣的是,如果我/usr/bin/ld用符号链接替换为/usr/bin/ld.lld,效果很好(没有错误,并且从编译的二进制文件中我看到它确实与 链接lld)。但是,我不想制作lld系统范围的链接器,我只想在特定的 Rust 板条箱中使用它。

那么更改默认 rustc 链接器的正确方法是什么?

kre*_*reo 16

感谢@Jmb 评论,我找到了解决方案。事实证明,使用的默认链接器rustc实际上是cc(这是有道理的 - 它提供了编译/链接 C 代码所需的所有默认值,这也适用于 Rust)。我们可以传递一个参数cc来使它与lld

[target.x86_64-unknown-linux-gnu]
rustflags = [
    "-C", "link-arg=-fuse-ld=lld",
]
Run Code Online (Sandbox Code Playgroud)

现在cargo buildlld.


Ami*_*adi 9

使用 lld将其添加到.cargo/config.toml(在项目中)强制中

[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "link-arg=-fuse-ld=lld"]

[target.x86_64-pc-windows-gnu]
rustflags = ["-C", "link-arg=-fuse-ld=lld"]

[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "linker=clang", "-C", "link-arg=-fuse-ld=lld"]
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅: https://github.com/rust-lang/rust/issues/71515

"-C", "linker=clang"如果您安装了 Gcc 9 或更高版本,则可以在 Linux 上删除


小智 5

这也有效,而且我认为@Jmb 确实问过这个问题。

rustflags = [
  "-C", "linker=clang-12",  # change the version as needed
]
Run Code Online (Sandbox Code Playgroud)