homeposts

Created: 6/10/2022

Cross Compilation from M1 Mac for Rust Projects

I had a really hard time Googling for answers to questions about cross compilation from an M1 mac, because historically there have been so many questions about compiling from x86_64 to arm; mostly in the embedded systems space.

I hope that I've thrown in enough keywords to bring people with the same problem as myself here:

I just want to compile my app on my mac and ship it to a Linux box running an x86_64 architecture and I am struggling.

Helpful Resources

The first resource, in particular, was most helpful to me, so I reduced it into a bash snippet.

The Snippet

This will setup tooling and cross-compile an x86_64 executable from your M1 Mac.

#!/bin/bash

# musl is a version of the C standard library that can be statically linked
rustup target add x86_64-unknown-linux-musl

# see https://github.com/messense/homebrew-macos-cross-toolchains
brew tap messense/macos-cross-toolchains
brew install x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu
echo "export CC_x86_64_unknown_linux_gnu=x86_64-unknown-linux-gnu-gcc
export CXX_x86_64_unknown_linux_gnu=x86_64-unknown-linux-gnu-g++
export AR_x86_64_unknown_linux_gnu=x86_64-unknown-linux-gnu-ar
export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=x86_64-unknown-linux-gnu-gcc" \
    >> ~/.bashrc
source ~/.bashrc

echo "[target.x86_64-unknown-linux-musl]
linker = \"x86_64-unknown-linux-gnu-gcc\"" >> ~/.cargo/config

# ---
# tooling setup is done
cargo build --release --target x86_64-unknown-linux-musl

caveats

  • you need to install homebrew
  • this assumes the use of bash and appends to ~/.bashrc
  • this is assumed to be run in the root of a Rust project, because it ends with cross-compiling a rust project

You now have a working cross-compiled executable in target/x86_64-unknown-linux-musl send it off to live its best x86_64 life!