将Rust应用程序从Linux交叉编译到Windows

基本上我正试图编译最简单的代码到Windows,而我正在Linux上开发。

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

我通过search互联网发现了这些命令:

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

可悲的是,他们没有一个工作。 它给了我一个关于标准箱失踪的错误

 $ 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 

有什么方法可以在Linux上编译将在Windows上运行的代码?

Rust分发版仅提供主机系统的编译库。 但是,根据Arch Linux在Rust上的wiki页面 ,您可以将系统中相应位置(在/usr/lib/rustlib 目录下)的编译库从下载目录中的Windows软件包(请注意有i686和x86-64软件包) /usr/lib/rustlib/usr/local/lib/rustlib ,取决于Rust的安装位置),安装mingw-w64-gcc和Wine,你应该可以交叉编译。

如果你正在使用Cargo,你可以通过将这个添加到~/.cargo/config (其中$ARCH是你使用的体系结构)来告诉Cargo在哪里寻找ar和链接器:

 [target.$ARCH-pc-windows-gnu] linker = "/usr/bin/$ARCH-w64-mingw32-gcc" ar = "/usr/$ARCH-w64-mingw32/bin/ar" 

注意:确切的路径可能会根据您的分布而有所不同。 检查您的发行版中的mingw-w64软件包文件列表(GCC和binutils)。

那么你可以像这样使用Cargo:

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

让我们将从rust-sdl2项目的例子从Ubuntu交叉编译到Windows x86_64

~/.cargo/config

 [target.x86_64-pc-windows-gnu] linker = "x86_64-w64-mingw32-gcc" ar = "x86_64-w64-mingw32-gcc-ar" 

然后运行这个:

 sudo apt-get install gcc-mingw-w64-x86-64 -y # use rustup to add target https://github.com/rust-lang-nursery/rustup.rs rustup target add x86_64-pc-windows-gnu # Based on instructions from https://github.com/AngryLawyer/rust-sdl2/ # First we need sdl2 libs # links to packages https://www.libsdl.org/download-2.0.php sudo apt-get install libsdl2-dev -y wget https://www.libsdl.org/release/SDL2-devel-2.0.4-mingw.tar.gz -P /tmp tar xf /tmp/SDL2-devel-2.0.4-mingw.tar.gz -C /tmp # Prepare files for building mkdir -p ~/projects cd ~/projects git clone https://github.com/AngryLawyer/rust-sdl2 cp -r /tmp/SDL2-2.0.4/x86_64-w64-mingw32/lib/* ~/.multirust/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-pc-windows-gnu/lib/ cp /tmp/SDL2-2.0.4/x86_64-w64-mingw32/bin/SDL2.dll ~/rust-sdl2/ # Build examples # we use loop for...in because there is no such feature in cargo to build all examples at once for i in examples/*; do cargo build --target=x86_64-pc-windows-gnu --verbose --example $(basename $i .rs); done 

cargo build将把二进制文件放在target/x86_64-pc-windows-gnu/debug/examples/

复制需要的文件:

 cp /tmp/SDL2-2.0.4/x86_64-w64-mingw32/bin/SDL2.dll ~/rust-sdl/target/x86_64-pc-windows-gnu/debug/examples/ cp ~/rust-sdl/tests/sine.wav ~/rust-sdl/target/x86_64-pc-windows-gnu/debug/examples/ 

然后将目录~/rust-sdl/target/x86_64-pc-windows-gnu/debug/examples/复制到你的Windows机器上并运行exe文件。

在cmd.exe中运行

如果您想在运行exe文件时看到控制台输出,可以从cmd.exe运行它们。

要在文件资源管理器中打开当前目录下的cmd.exe ,在窗口的空白处点击鼠标右键,在Open command window here选择Open command window here

没有mingw回溯 – 使用msvc

与此同时,如果你想要回溯,不介意安装VC ++,你可以使用Rust的x86_64-pc-windows-msvc版本。

https://github.com/rust-lang/rust/issues/33985#issuecomment-222826116