I recently had to cross-compile my Rust app from macOS to Linux. The process wasn't too hard, but the documentation wasn't as easy to find as I'd like it to be. Hence, I'm documenting the process here.
First, add the appropriate target to your Rust toolchain:
$ rustup target add x86_64-unknown-linux-musl
$ brew install filosottile/musl-cross/musl-cross
Now that you have added the target and installed the linker, make sure your ~/.cargo/config has the following info in it:
[target.x86_64-unknown-linux-musl] linker = "x86_64-linux-musl-gcc"
Once have completed the previous steps, you should be able to cross-compile your Rust app from macOS to Linux with the following command:
$ cargo build --release --target x86_64-unknown-linux-musl
Personally, I find the previous command too long to remember, and I don't feel like having a Makefile in my apps for it. After reading about how to extend Cargo with new subcommands, I wanted to make a
linux subcommand that would do the cross-compilation for me.
For this to work, you need to create a file named
cargo-linux and make sure it is in your $PATH. I ended up placing my file in
~/.cargo/bin/ which is already in my $PATH. The file has the following contents:
#/usr/bin/env bash cargo build --release --target x86_64-unknown-linux-musl
After doing this, I can now just run
cargo linux in the main directory of my Rust projects to cross-compile to Linux.