cross compile rust
problem: compiling on mac m1 and to linux results in 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
- arm64 vs. x86_64: the mac m1 uses arm64 architecture, while many linux systems use x86_64. binaries compiled for arm64 are not natively executable on x86_64 hardware because the instruction sets are fundamentally different.
- instruction set differences: arm64 and x86_64 have different sets of cpu instructions. an arm64 binary includes instructions that can only be executed by an arm64 processor, making it incompatible with an x86_64 processor.
system libraries and abis
- different operating systems: macos and linux have distinct system environments. binaries compiled on macos expect macos-specific system libraries, frameworks, and abis (application binary interfaces). these dependencies are not present on a linux system.
- abi incompatibility: the abi defines how functions are called and how different data types are handled at the binary level. macos and linux have different abis, making binaries incompatible across these systems.
system calls and runtime environment
- system calls: a binary compiled on macos will use macos-specific system calls for interacting with the os kernel, which are different from linux system calls. these differences mean that even if the cpu architecture were the same, the binary would fail to execute correctly on linux.
- runtime environment: macos provides a different runtime environment compared to linux, including differences in file system layout, available system services, and default environment variables.
solution: cross compile rust for linux
determine machine architecture
figure out the architecture of the target machine (ec2 instance for example):
cross compile for linux
use https://github.com/messense/homebrew-macos-cross-toolchains and compile for linux:
and compile for linux:
fixing compile errors
openssl gives errors on compile. instead of relying on the system openssl, use the https://docs.rs/openssl/0.10.29/openssl/#vendored feature: