Search code examples
rustlinkerrust-cargomold

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

  • 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)