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

why?

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
x86_64

cross compile for linux

use https://github.com/messense/homebrew-macos-cross-toolchains 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

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 https://docs.rs/openssl/0.10.29/openssl/#vendored feature:

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