Quick: cross compile Rust from MacOS to Linux
20 Jun 20201. Add Linux target #
rustup target add x86_64-unknown-linux-musl
We're using the x86_64-unknown-linux-musl
target so that the binary is statically linked. The x86_64-unknown-linux-gnu
target will dynamically link to libc if using std.
2. Install linker #
brew install FiloSottile/musl-cross/musl-cross
There is a bottle for Catalina (at the time of writing); other versions will compile from scratch. This took me almost 25m.
3. Tell Cargo about the linker #
Create a Cargo config file if you don't have one in your project root or home directory.
mkdir .cargo
touch .cargo/config
Add the linker attribute to point Cargo to the right binary in your Cargo config file:
[target.x86_64-unknown-linux-musl]
linker = "x86_64-linux-musl-gcc"
4. Compile #
cargo build --target x86_64-unknown-linux-musl
You'll find the compiled binaries in inside target/x86_64-unknown-linux-musl/debug
(or release with --release).