Skip to content

Instantly share code, notes, and snippets.

@ronlobo
Forked from Mefistophell/RUST.MD
Created November 6, 2023 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronlobo/03ed91433e1b7df76082db1a2585b09c to your computer and use it in GitHub Desktop.
Save ronlobo/03ed91433e1b7df76082db1a2585b09c to your computer and use it in GitHub Desktop.
How to Compile a Rust Program on Mac for Windows

Question: I want to compile my Rust source code for the Windows platform but I use macOS.

Solution:

  1. Install target mingw-w64: brew install mingw-w64
  2. Add target to rustup: rustup target add x86_64-pc-windows-gnu
  3. Create .cargo/config
  4. Add the instructions below to .cargo/config
[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"
  1. If it's not working try to run the following command:
cp -f /usr/local/Cellar/mingw-w64/7.0.0_1/toolchain-x86_64/x86_64-w64-mingw32/lib/{,dll}crt2.o `rustc --print sysroot`/lib/rustlib/x86_64-pc-windows-gnu/lib
  1. And finally, run: cargo build --target=x86_64-pc-windows-gnu --verbose

Useful commands:

rustup show — shows targets amn toolchain

rustup target list — shows all supported targets

A bit of theory:

To compile a source code for a platform different from your local, you need to specify a target. This tells the compiler which platform your code should be compiled for. For this reason, you need to install the appropriate GCC, the GNU Compiler Collection for Windows. Like this one: mingw-w64.

Then you should add the target to the Rust toolchain.

Toolchains are a set of linked tools that help the language produce a functional target code. They can provide extended functionality from either a simple compiler and linker program, or additional libraries

The next step is to add a linker. This can be set in the Cargo config

The Rust compiler sequentially goes through each source code file in your program and checks your code to make sure it follows the rules of the Rust language and translates your source code into a machine language file called an object file. After the compiler creates one or more object files, then another program called the linker take all the object files generated by the compiler and combine them into a single executable program. In addition to being able to link object files, the linker also is capable of linking library files. A library file is a collection of precompiled code that has been “packaged up” for reuse in other programs.

When the linker is added you can build a program.

Links:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment