3

在 Arch Linux 下为 Windows 编译 Rust 程序

 2 years ago
source link: https://blog.nanpuyue.com/2019/052.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

假设已经安装了 Rust 的工具链。

添加 x86_64-pc-windows-gnu target:

rustup target add x86_64-pc-windows-gnu

安装 mingw-w64 工具链:

pacman -S mingw-w64-crt mingw-w64-binutils mingw-w64-winpthreads mingw-w64-headers mingw-w64-gcc

设置链接器

~/.cargo/config 中加入以下内容:

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

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

差不多可以尝试编译了,我试了一下之前自己写的那个 sha256 库:

git clone https://github.com/nanpuyue/sha256
cd sha256
cargo build --release --target x86_64-pc-windows-gnu --example sha256sum

结果得到了如下错误:

  = note: /usr/lib/gcc/x86_64-w64-mingw32/8.3.0/../../../../x86_64-w64-mingw32/bin/ld: /home/nanpuyue/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-pc-windows-gnu/lib/crt2.o:crtexe.c:(.rdata$.refptr.__onexitbegin[.refptr.__onexitbegin]+0x0): undefined reference to `__onexitbegin'
          /usr/lib/gcc/x86_64-w64-mingw32/8.3.0/../../../../x86_64-w64-mingw32/bin/ld: /home/nanpuyue/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-pc-windows-gnu/lib/crt2.o:crtexe.c:(.rdata$.refptr.__onexitend[.refptr.__onexitend]+0x0): undefined reference to `__onexitend'
          collect2: 错误:ld 返回 1

查了一下,找到了这个:https://github.com/rust-lang/rust/issues/48272#issuecomment-429596397

简单的说就是 Rust 工具链中自带的 crt2.o 太老了,我们替换一下:

cp -vb /usr/x86_64-w64-mingw32/lib/crt2.o "$(rustc --print sysroot)"/lib/rustlib/x86_64-pc-windows-gnu/lib/

再重新编译,看起来问题不大:

cargo_build_x86_64-pc-windows-gnu

它甚至能运行:

run_sha256sum.png


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK