Cross compile Rust programs to the MSVC Windows target in WSL, inspired by msvc-wine-rust
Visit here:
https://visualstudio.microsoft.com/downloads/
Then download Visual Studio
and then install Desktop development with C++
workload.
Or just download Build Tools for Visual Studio
and then install C++ Build Tools
workload.
First, add msvc
targets using rustup
:
rustup target add x86_64-pc-windows-msvc
rustup target add i686-pc-windows-msvc
Then, clone the repo to WSL somewhere, ~/.local/share
is a good place.
git clone https://github.com/strickczq/msvc-wsl-rust.git msvc-linker
chmod a+x msvc-linker/*.sh
Last, edit the linker config found in config.sh
, as msvc path and version may vary from
person to person. The file has instructions on how to find the information you need.
First, your project has to be in the Linux filesystem. The mounted Windows drives can't be
accessed though \\wsl.localhost\
which will cause the linker to fail, saying it can't open
the target binary (i.e. the outfile for the linking stage).
If the linker fails saying it can't open
last-linking-args.txt
, this may be because you have an old version of WSL, where the network path is\\wsl\$\
, not\\wsl.localhost\
. Otherwise it may be because you've got the WSL distro wrong inconfig.sh
.
For x86_64 target:
rustc -C linker="/path/to/msvc-linker/linker-x64.sh" --target x86_64-pc-windows-msvc your_code.rs
And for x86 target:
rustc -C linker="/path/to/msvc-linker/linker-x86.sh" --target i686-pc-windows-msvc your_code.rs
You need to put this into ~/.cargo/config.toml
first (you may need to create the file):
[target.x86_64-pc-windows-msvc]
linker = ".local/share/msvc-linker/linker-x64.sh"
rustflags = ["-Ctarget-feature=+crt-static"]
[target.i686-pc-windows-msvc]
linker = ".local/share/msvc-linker/linker-x86.sh"
rustflags = ["-Ctarget-feature=+crt-static"]
Cargo config file paths are relative to the config file location! Read more here. Passing a compiler flag for static build is totally optional, but saves you having to deal with missing dlls later.
For x86_64 target:
cargo build --target x86_64-pc-windows-msvc
For x86 target:
cargo build --target i686-pc-windows-msvc
cargo run --target x86_64-pc-windows-msvc
cargo run --target i686-pc-windows-msvc
Licensed under Apache License 2.0. For details, see the LICENSE file.