关于rust:Rust-交叉编译-macOS-为-Linux-和-Windows

8次阅读

共计 2142 个字符,预计需要花费 6 分钟才能阅读完成。

前言

鉴于 rust 中文材料较少,遇到问题的解决方案更少。这里记录遇到的一些问题。
Rust 反对穿插编译,能够在 macOS 平台编译出 Linux 或者 Windows 可运行的程序,或者在 Linux 平台编译 macOS 或者 Windows 可运行的程序。> > 本文次要文章解说 Mac 平台编译为其余平台的二进制程序。
想要实现跨平台编译且可运行的程序,那么咱们就须要动态链接,这样生成程序才不会因为动态链接库的起因运行失败。
默认状况下,Rust 动态连贯所有 Rust 代码。如果程序中应用了规范库,Rust 会连贯到零碎的 libc 实现。

环境

苹果零碎:操作系统:macOS 12.3.1 21E258 x86_64 生锈:rustc 1.60.0 (7737e0b5c 2022-04-04) 生锈:rustup 1.24.3 (ce5817a94 2021-05-31)
Linux:操作系统:EndeavourOS Linux x86_64 外围:5.17.1-arch1-1 生锈:rustc 1.60.0 (7737e0b5c 2022-04-04) 生锈:rustup 1.24.3 (ce5817a94 2021-05-31)
首先须要装置 Rust,应用命令。

案例

应用 Cargo 新建二进制我的项目:
cargo new –bin hello
文件 main.rs:
fn main() {
println!(“Hello World!\n”);
}
macOS 编译为 Linux 和 Windows 可用二进制程序
编译为 Linux 平台
想要实现 Linux 平台能够运行的程序,那么就须要应用 musl 来代替 glibc,musl 实现了 Linux libc。
musl 在 macOS 上应用 musl-cross,musl-cross 是专门编译到 Linux 的工具链,上面进行装置:
musl https://musl.libc.org/
$ brew install FiloSottile/musl-cross/musl-cross
还须要创立 musl-gcc:
$ ln -s /usr/local/bin/x86_64-linux-musl-gcc /usr/local/bin/musl-gcc
增加对应的 Target,只须要执行一次就能够了:
rustup target add x86_64-unknown-linux-musl
批改配置文件~/.cargo/config(如果没有能够新建),增加以下内容:
[target.x86_64-unknown-linux-musl]
linker = “x86_64-linux-musl-gcc”
也能够在我的项目根目录下创立 .cargo/config 文件,只对以后我的项目失效

应用
cargo build –release –target x86_64-unknown-linux-musl
后果:
$ tree -L 2 target/x86_64-unknown-linux-musl
target/x86_64-unknown-linux-musl
├── CACHEDIR.TAG
└── debug
├── build
├── deps
├── examples
├── hello
├── hello.d
└── incremental
5 directories, 3 files
$ file target/x86_64-unknown-linux-musl/debug/hello
target/x86_64-unknown-linux-musl/debug/hello: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), static-pie linked, with debug_info, not stripped

编译为 Windows 平台

mingw-w64 是用来编译到 Windows 的工具链,应用如下命令进行装置:
brew install mingw-w64
增加接下来 mingw-64 的 Target,只须要执行一次就能够了:
$ rustup target add x86_64-pc-windows-gnu
批改配置文件~/.cargo/config(如果没有能够新建),设置 Linker,增加如下内容:
[target.x86_64-pc-windows-gnu]
linker = “x86_64-w64-mingw32-gcc”
ar = “x86_64-w64-mingw32-gcc-ar”

应用
$ cargo build –release –target x86_64-unknown-linux-musl

后果

$ tree -L 2 target/x86_64-pc-windows-gnu
target/x86_64-pc-windows-gnu
├── CACHEDIR.TAG
└── debug
├── build
├── deps
├── examples
├── hello.d
├── hello.exe
└── incremental
5 directories, 3 files
$ file target/x86_64-pc-windows-gnu/debug/hello.exe
target/x86_64-pc-windows-gnu/debug/hello.exe: PE32+ executable (console) x86-64, for MS Windows

正文完
 0