Skip to content

Speeding up Rust compilations on macOS

Posted on:May 2, 2024

Ever noticed how the final leg of your build process crawls to a finish, even on the most cutting-edge Mac Silicon chip? That sluggish culprit is none other than the linker, a crucial but often overlooked component of the compilation journey.

Let’s dive into how you can supercharge this process by switching to a faster, more efficient linker called sold. It’s something you only need to install once and then forever reap the benefits of faster compile times.

If, like me, you don’t mind pasting random shell commands into the machine that holds your precious photos and documents, then follow along below. If you’re more discerning and want to understand what a linker is and why it’s useful then I recommend reading about mold, the linker sold is forked from.

Step 1: Summoning sold

First, prepare your environment by stepping into the transient realm of a temporary directory:

cd /tmp
git clone git@github.com:bluewhalesystems/sold.git

Next, engage in the ancient craft of compiling from source:

cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=c++ -B build
cmake --build build -j$(nproc)
sudo cmake --build build --target install
cd ..
rm -rf sold

What this sequence does is materialise sold in your local bin folder. Check its existence with:

which ld64.sold

If the terminal echoes back a path, congratulations, the summoning was successful.

Step 2: Configuring Rust to use sold

Now, for the real magic—configuring your Rust projects to use this newly summoned linker. You’ll need to tweak or create a specific tome in your project’s .cargo directory:

  1. Navigate or create a .cargo/config.toml within your project directory. Note that this is NOT your Cargo.toml.
  2. Inject the following incantation:
[target.aarch64-apple-darwin]
rustflags = ["-C", "link-arg=-fuse-ld=/usr/local/bin/ld64.sold"]

This addendum tells the Rust compiler to use your new linker.

Step 3: Recompilation

Trigger a recompilation. The initial run will recompile everything, so it might take a bit. However, subsequent builds should be noticeably faster.

cargo build --release

Conclusion

Congratulations! You should now have faster compile times for both debug and release builds.

For more ways to optimise and speed up compilations I highly recommend the relevant section in the Rust Performance Book or using Cargo Wizard if you just want it ‘done for you’.