cross compile rust

problem: compiling on mac m1 and to linux results in error:

Terminal window
-bash: ./rust-app: cannot execute binary file: Exec format error


compiling a rust program on a mac m1 and running it on a linux system is not straightforward due to several technical reasons:

architectural mismatch

system libraries and abis

system calls and runtime environment

solution: cross compile rust for linux

determine machine architecture

figure out the architecture of the target machine (ec2 instance for example):

Terminal window
[email protected]:~$ uname -m

cross compile for linux

use and compile for linux:

Terminal window
brew tap messense/macos-cross-toolchains
# install x86_64-unknown-linux-gnu toolchain
brew install x86_64-unknown-linux-gnu

now add the linker to the Cargo.toml file:

linker = "x86_64-unknown-linux-gnu-gcc"

and compile for linux:

Terminal window
cargo build --target x86_64-unknown-linux-gnu

fixing compile errors

Terminal window
export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=x86_64-linux-gnu-gcc

openssl gives errors on compile. instead of relying on the system openssl, use the feature:

openssl-src = { version = "111.0.1", features = ["vendored"] }