rust程序静态编译的两种方法总结

1. 概述

经过我的探索,总结了两种rust程序静态编译的方法,理论上两种方法都适用于windows、mac os和linux(mac os未验证),实测方法一性能比方法二好,现总结如下,希望能够帮到你.

2.方法一

2.1 添加配置文件

在项目的同级文件夹下新建".cargo/config.toml"文件,根据使用的系统,添加下面的配置

toml 复制代码
#windows
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]`
toml 复制代码
#linux
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "target-feature=+crt-static"]

理论上mac os也可以,将[target.x86_64-unknown-linux-gnu]替换为自己使用的工具链就可以了

2.2 打包运行

2.2.1 winsows

在windows下运行cargo build --release就可以直接打包为静态链接的程序了;

2.2.2 linux

在linux下运行cargo build --release --target=x86_64-unknown-linux-gnu,可能会出现如下提示
/usr/bin/ld: cannot find -lxxx,这是缺少gcc-libc的静态库文件

需要安装的有两个glibc-static和libstdc++-static;

在这里可以找到这两个静态库: https://oraclelinux.pkgs.org/

这里是oracle linux9 的链接:https://oraclelinux.pkgs.org/9/ol9-codeready-builder-x86_64/glibc-static-2.34-125.0.1.el9_5.8.x86_64.rpm.html, https://oraclelinux.pkgs.org/9/ol9-codeready-builder-x86_64/libstdc++-static-11.5.0-5.0.1.el9_5.x86_64.rpm.html

注意要选择自己对应的系统!!!

页面向下拉,有个install howto 的标题,直接运行里面的命令(如截图里的dnf --enablerepo=ol9_codeready_builder install libstdc++-static)就可以安装了,安装完就可以愉快的打包了;

3.方法二

复制代码
此方法为使用musl库打包为静态链接,参考我的另一篇文章,实测该方法打包的静态文件性能会比gcc稍差一点;

使用musl将rust程序静态编译

4.总结

优先推荐使用方法一,但据网友说方法一某些库无法成功打包,此时可以考虑采用方法二的方式打包,但会有性能损失,需自行考量。

以上

相关推荐
zzu123zsw1 小时前
为什么 Python 做 Agent 总在并发中崩溃?拆解 Blockcell 在 Rust 下的 Host-Cell 隔离与自愈状态机
开发语言·python·rust·大模型·ai agent
hsg772 小时前
简述:基于Ubuntu24编译发布rust开发的html+web后端服务的方法
rust·1024程序员节
zzu123zsw3 小时前
当 GPU 加速渲染遇上无头组件:拆解 Yororen UI 在 GPUI 生态下的状态解耦与 XML 模板实践
xml·ui·rust·gui·gpui
传奇开心果编程12 小时前
【Rust入门练中学】第6课:结构体与方法
开发语言·rust·结构体·编程语言理论·结构体方法·编程通用语言
本地化文档12 小时前
cutile-rs-book-l10n
rust·gpu·nvidia·cuda·sphinx·crowdin
qq_4069810315 小时前
大白话rust系列09 函数调用两次有什么错?
开发语言·python·rust
康小旺16 小时前
TypeScript 编译器开始卷 Rust 了:Cloudflare 的 tsrs 到底想干嘛?
rust·typescript
Norna17 小时前
时间轮的 +1,为什么最后只留在顶层
rust
轻舟技术A1 天前
Rust 重写 Pi:会话启动耗时降 91%,就绪内存少 78%
开发语言·后端·rust
unconditional1 天前
外部命令改不了你的 shell:sdkm 怎么做到"回车即生效"
rust·开源