Fedcomp Fedcomp - 11 months ago 168
Linux Question

Cross-compile a Rust application from Linux to Windows

Basically I'm trying to compile the simplest code to Windows while I am developing on Linux.

fn main() {
println!("Hello, and bye.")

I found these commands by searching the internet:

rustc --target=i686-w64-mingw32-gcc main.rs
rustc --target=i686_pc_windows_gnu -C linker=i686-w64-mingw32-gcc main.rs

Sadly, none of them work. It gives me an error about the std crate missing

$ rustc --target=i686_pc_windows_gnu -C linker=i686-w64-mingw32-gcc main.rs

main.rs:1:1: 1:1 error: can't find crate for `std`
main.rs:1 fn main() {
error: aborting due to previous error

Is there a way to compile code on Linux that will run on Windows?

Answer Source

The Rust distribution only provides compiled libraries for the host system. However, according to Arch Linux's wiki page on Rust, you could copy the compiled libraries from the Windows packages in the download directory (note that there are i686 and x86-64 packages) in the appropriate place on your system (in /usr/lib/rustlib or /usr/local/lib/rustlib, depending on where Rust is installed), install mingw-w64-gcc and Wine and you should be able to cross-compile.

If you're using Cargo, you can tell Cargo where to look for ar and the linker by adding this to ~/.cargo/config (where $ARCH is the architecture you use):

linker = "/usr/bin/$ARCH-w64-mingw32-gcc"
ar = "/usr/$ARCH-w64-mingw32/bin/ar"

Note: the exact paths can vary based on your distribution. Check the list of files for the mingw-w64 package(s) (GCC and binutils) in your distribution.

Then you can use Cargo like this:

$ # Build
$ cargo build --release --target "$ARCH-pc-windows-gnu"
$ # Run unit tests under wine
$ cargo test --target "$ARCH-pc-windows-gnu"