Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the default rustc / Cargo linker?

Tags:

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 

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 

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.

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.

So what is the proper way to change the default rustc linker?

like image 217
kreo Avatar asked Sep 05 '19 20:09

kreo


People also ask

What linker does Rust use?

In both cases the Rust code has to be compiled with -C linker-plugin-lto and the C/C++ code with -flto or -flto=thin so that object files are emitted as LLVM bitcode.

Where is the cargo config file?

Configuration values with sensitive information are stored in the $CARGO_HOME/credentials. toml file. This file is automatically created and updated by cargo login .

Does Rust use LLD?

lld is not fully supported for use with Rust, but it should work for most use cases on Linux and Windows. There is a GitHub Issue tracking full support for lld.


2 Answers

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", ] 

Now cargo build links with lld.

like image 163
kreo Avatar answered Sep 22 '22 17:09

kreo


This also works and is what I think @Jmb actually asked.

rustflags = [   "-C", "linker=clang-12",  # change the version as needed ] 
like image 38
Rin Avatar answered Sep 22 '22 17:09

Rin