20

I wrote a little game using Rust, and I used cargo build --release to compile a release version on Mac.

I tried to share this with my friend who is using Ubuntu, but when he tried to run the binary, he got the following error:

cannot execute binary file: Exec format error

I searched for this but found no answers. Doesn't Rust claim to have "no runtime"? Shouldn't it be able to run anywhere in binary form?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
FrontMage
  • 641
  • 1
  • 5
  • 13

2 Answers2

24

Rust not having a runtime means that it doesn't have a lot of code running as part of the language (for example a garbage collector or bytecode interpreter). It does still need to use operating system primitives (i.e. syscalls), and these are different on MacOS and Linux.

What you want is a cross compiler. If you're using rustup, then installing a cross compiler should be simple:

# Install the toolchain to build Linux x86_64 binaries
rustup target add x86_64-unknown-linux-gnu

Then building is:

cargo build --release --target=x86_64-unknown-linux-gnu

Caveat: I don't have an OS X machine to test this on; please comment or edit to fix this if it works!

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Chris Emerson
  • 13,041
  • 3
  • 44
  • 66
  • 2
    I tried, I think you might have to install `x86_64-linux-gnu-gcc` then add a `linker` to `.cargo/config` to make that work. – FrontMage Jan 22 '17 at 03:53
  • 6
    @FrontMage -- how do you install `x86_64-linux-gnu-gcc` on Mac? – Digant C Kasundra Mar 17 '17 at 17:41
  • 10
    This does not produce a binary: `error: linking with \`cc\` failed:` ... `= note: clang: warning: argument unused during compilation: '-pie' [-Wunused-command-line-argument] ld: unknown option: --as-needed clang: error: linker command failed with exit code 1 (use -v to see invocation)` – Shepmaster Oct 13 '18 at 16:14
  • @Shepmaster i have the same issue while compiling from linux to mac do you have any idea about the solution ? – nikoss Feb 08 '19 at 08:58
  • `brew install rustup-init && rustup-init` – hobs Feb 24 '19 at 04:55
  • 5
    @Shepmaster you may need to install the linker, `brew install FiloSottile/musl-cross/musl-cross` or `brew install gcc`, and add it to `.cargo/config` – PapEr Apr 16 '19 at 05:46
4

Well, it is because Rust has no runtime (unlike e.g. Java's JVM) that you can't just compile code on one OS and expect it to run on a different one; what you are looking for is cross-compilation. I haven't done it in Rust, but from what I can gather you can find relevant information on different cross-compilation Rust strategies on this GitHub repo.

ljedrz
  • 20,316
  • 4
  • 69
  • 97