阅读资料
Everything you need to know about cross compiling Rust programs!(2017年停止更新了):https://github.com/japaric/rust-cross
windows 下编译成 linux 文件
描述
默认 windows 安装的rust 是 x86_64-pc-windows-msvc 版本的,且会动态链接到 MSVCRT。交叉编译需要静态链接(也就是执行文件的某些代码 需要 copy 一份),因此需要在
.cargo/config
文件(不存在就需要创建一个)中指明:[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
添加这个命令前编译生成的文件的体积比添加后的体积大,因为静态链接增加了 MSVCRT 的一些内容。如果不再需要交叉编译,就把 config 文件的这部分删掉。
_crt-static_
功能解决了我们的发行问题。对于 Linux,我们将静态链接 musl libc,因为它在构建时对我们来说更方便(并且更可移植)。musl是一个完整的,自包含的 Linux libc,没有系统依赖性。这意味着我们不必提供Linux系统库来动态链接到Windows构建环境中。musl解决了我们的交叉编译问题。给 Rust 安装 linux-musl target:命令行输入
rustup target add x86_64-unknown-linux-musl
使用 LLVM 作为连接工具(Rust 已自带),因此在 config 中声明一下:
[target.x86_64-unknown-linux-musl]
linker = "rust-lld"
编译时指定 target(不指定情况下会根据主机系统情况,也就是生成 x86_64-pc-windows-msvc 版本):
cargo build --target x86_64-unknown-linux-musl
MWE
.cargo/config
文件写入内容: ```bash [target.x86_64-unknown-linux-musl] linker = “rust-lld”
[target.x86_64-pc-windows-msvc] rustflags = [“-C”, “target-feature=+crt-static”]
2. 命令行:
```bash
cargo new cross-compile
cd cross-compile
cargo build --target x86_64-unknown-linux-musl
cargo new 会自动创建一个 printn!("Hello, world!");
的项目
- 编译后的文件在
.\target\x86_64-unknown-linux-musl\debug
下 - 复制到 linux 系统,使用
chmod +x cross-compile
和./cross-compile
运行即可出现 “Hello, world!”。 - 使用 upx 工具压缩、在 linux 平台编译相同的程序及压缩 体积比较: | 单位:K | debug 版 | | release 版 | | | —- | —- | —- | —- | —- | | | windows 交叉编译 | linux 编译 | windows 交叉编译 | linux 编译 | | UPX 压缩前 | 3620 | 3133 | 3609 | 3119 | | UPX 压缩后 | 890 | 730 | 884 | 压缩出错 |
linux 下编译成 windows 文件
linux 需要 msvs 环境或者 gnu 的 C 链接器才能编译成 exe 文件:
https://github.com/rust-lang/rustup/issues/1470
https://www.reddit.com/r/rust/comments/5k8uab/crosscompiling_from_ubuntu_to_windows_with_rustup/
网上推荐的是 mingw-w64
。
# mingw-w64 至少需要 875 M 硬盘空间
sudo apt install mingw-w64
# Rust 增加对 x86_64-pc-windows-gnu 平台的支持
rustup target add x86_64-pc-windows-gnu
# 编译项目时
cargo build --target x86_64-pc-windows-gnu
针对 Rust Book 的 IO 例子 minigrep(命令行工具,输入查询词,打印包含查询词的行,并且支持大小写不敏感参数和环境变量),比较一下 exe 二进制文件的体积。 | 单位:K | debug 版 | | release 版 | | | —- | —- | —- | —- | —- | | | linux 交叉编译 | windows 编译 | linux 交叉编译 | windows 编译 | | 压缩前 | 4787 | 272 | 1434 | 198 | | 压缩后 | 1062 (strip) | 102 (upx) | 342 (strip) | 82 (upx) | | 二次压缩后 | 360 (strip+upx) | / | / | / | | 最终压缩率 | 7.5% | 37.5% | 23.8% | 41.4% |
此处 upx 是在 windows 下运行的。
源代码和二进制文件:minigrep.zip