macOS下Rust跨平台交叉编译linux或windows应用

在默认情况下,Rust静态连接所有 Rust 代码。如果程序中使用了标准库,Rust 会连接到系统的 libc 实现。

首先需要安装 Rust,使用来自官方的命令 curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

示例一个Demo代码

使用 Cargo 新建二进制项目

cargo new --bin hello

文件 main.rs

fn main() {
    println!("Hello World!n");
}

macOS 编译为 Linux 和 Windows 可用二进制程序

编译为 Linux 平台

要实现 Linux 平台可以运行的程序,那么需要使用 musl 来替代 glibcmusl 实现了Linux libc

macOS 上使用 musl-cross, musl-cross 是用来专门编译到 Linux 的工具链, 下面进行安装:

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
└── release
    ├── build
    ├── deps
    ├── examples
    ├── hello
    ├── hello.d
    └── incremental

5 directories, 3 files
$ file target/x86_64-unknown-linux-musl/release/hello
target/x86_64-unknown-linux-musl/release/hello: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), static-pie linked, with debug_info, not stripped

如果遇到

error: failed to run custom build command for `rust-crypto v0.2.36

这个错误,解决:修改Cargo.toml , 因为rust-crypto这货太老了,也不维护了

[dependencies] 
# rust-crypto = "0.2.36"
sha2 = "0.10.6"
sha3 = "0.10.6"

编译为 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
└── release
    ├── build
    ├── deps
    ├── examples
    ├── hello.d
    ├── hello.exe
    └── incremental

5 directories, 3 files
$ file target/x86_64-pc-windows-gnu/release/hello.exe
target/x86_64-pc-windows-gnu/release/hello.exe: PE32+ executable (console) x86-64, for MS Windows

标签: macOS, Rust

相关文章

macOS下使用UTM安装Alpine Linux虚拟机

在macOS下使用UTM(Universal Turing Machine)安装Alpine Linux虚拟机是一个相对简单的过程,但需要一些基本的配置和步骤。以下是详细的指南,涵盖了从安装UT...

推荐几款在macOS下可以运行本地AI模型的软件

至于为嘛要在本地跑模型,我就不分析原因了,在macOS 14(Sonoma)上,有许多支持本地运行AI模型的软件,尤其是为了方便用户在本地运行LLM(大语言模型)和其他机器学习模型。以下是一些常...

图片Base64编码

CSR生成

图片无损放大

图片占位符

Excel拆分文件