'How to use the mold linker with cargo?

I'm using lld as my linker currently for Rust, but recently encountered the mold project, which is faster than lld. I'd like to try it for Rust compilation, but I'm not sure how to pass it in as my linker. In my .cargo/config file I've got:

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

But I can't just change that lld to mold, or provide the path to the mold executable. Is there a way to get gcc to accept a path to a linker?



Solution 1:[1]

Mold can now be used with Clang by simply adding this to ~/.cargo/config.toml

[target.x86_64-unknown-linux-gnu]
linker = "/usr/bin/clang"
rustflags = ["-C", "link-arg=--ld-path=/usr/bin/mold"]

Note: Mold may be installed at /usr/local/bin/mold if installed from source so the flags should be rustflags = ["-C", "link-arg=--ld-path=/usr/local/bin/mold"]. Run $ which mold to double check where it's installed

You can check it's worked by running readelf -p .comment target/<type>/<binary_name>

$ readelf -p .comment target/debug/my_binary

String dump of section '.comment':
  [     0]  GCC: (GNU) 11.1.0
  [    13]  mold 1.0.0 (compatible with GNU ld and GNU gold)

Solution 2:[2]

gcc does not accept an arbitrary path as an argument for -fuse-ld, unfortunately. Instead of tweaking .cargo/config file, try running cargo build as path/to/mold -run cargo build. By doing this, cargo runs under an influence of mold, and all invocations of /usr/bin/ld, /usr/bin/ld.gold and /usr/bin/ld.lld are intercepted and replaced by mold.

Solution 3:[3]

First, create a symlink of mold to lld to trick rust into believing it's ld.lld.

sudo ln -s /usr/bin/ld.mold /usr/bin/ld.lld 

Then add this in your ~/.cargo/config file to specify ld.lld (which is now mold)

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

Now build without mold -run and read the comment (readelf -p .comment target/debug/program-name)

String dump of section '.comment':
  [     0]  GCC: (GNU) 11.1.0
  [    13]  mold 0.9.3 (compatible with GNU ld and GNU gold)

I'm not really sure how it is that I can set a symlink as ld.lld, I guess I don't have that file currently, but nonetheless this is very hacky and serves to fool any future compiler into using mold, while believing it's using lld (if it's set to use lld). I use this personally because I don't like typing mold -run every time, though.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Rui Ueyama
Solution 3 Rustacean