操作方法
以下操作基于windows测试
创建hello world项目
cargo new hello-rust
编译
cargo build --release
输出日志
F:\project\rust\hello-rest>cargo build --release Compiling hello-rest v0.1.0 (F:\project\rust\hello-rest) Finished release [optimized] target(s) in 1.37s
查看文件大小
F:\project\rust\hello-rest\target\release 的目录 2022/07/10 17:43 <DIR> . 2022/07/10 17:43 <DIR> .. 2022/07/10 17:29 0 .cargo-lock 2022/07/10 17:29 <DIR> .fingerprint 2022/07/10 17:29 <DIR> build 2022/07/10 17:43 <DIR> deps 2022/07/10 17:29 <DIR> examples 2022/07/10 17:29 97 hello-rest.d 2022/07/10 17:43 155,648 hello-rest.exe //152KB 2022/07/10 17:43 1,232,896 hello_rest.pdb 2022/07/10 17:29 <DIR> incremental 4 个文件 1,388,641 字节 7 个目录 4,129,562,624 可用字节
新增优化参数
打开Cargo.toml新增如下内容
[profile.release] opt-level = 'z' # Optimize for size lto = true codegen-units = 1 panic = 'abort'
再次编译并查看文件大小
F:\project\rust\hello-rest>cargo build --release Compiling hello-rest v0.1.0 (F:\project\rust\hello-rest) Finished release [optimized] target(s) in 7.52s F:\project\rust\hello-rest>dir target\release 驱动器 F 中的卷没有标签。 卷的序列号是 64EE-EC8A F:\project\rust\hello-rest\target\release 的目录 2022/07/10 17:43 <DIR> . 2022/07/10 17:43 <DIR> .. 2022/07/10 17:29 0 .cargo-lock 2022/07/10 17:29 <DIR> .fingerprint 2022/07/10 17:29 <DIR> build 2022/07/10 17:45 <DIR> deps 2022/07/10 17:29 <DIR> examples 2022/07/10 17:29 97 hello-rest.d 2022/07/10 17:45 133,632 hello-rest.exe //130KB 2022/07/10 17:45 1,232,896 hello_rest.pdb 2022/07/10 17:29 <DIR> incremental 4 个文件 1,366,625 字节 7 个目录 4,129,583,104 可用字节
将优化后的方案使用upx压缩
压缩后的文件体积
F:\project\rust\hello-rest>dir target\release 驱动器 F 中的卷没有标签。 卷的序列号是 64EE-EC8A F:\project\rust\hello-rest\target\release 的目录 2022/07/10 17:48 <DIR> . 2022/07/10 17:48 <DIR> .. 2022/07/10 17:29 0 .cargo-lock 2022/07/10 17:29 <DIR> .fingerprint 2022/07/10 17:29 <DIR> build 2022/07/10 17:45 <DIR> deps 2022/07/10 17:29 <DIR> examples 2022/07/10 17:29 97 hello-rest.d 2022/07/10 17:45 62,464 hello-rest.exe //61KB 2022/07/10 17:45 1,232,896 hello_rest.pdb 2022/07/10 17:29 <DIR> incremental 4 个文件 1,295,457 字节 7 个目录 4,129,517,568 可用字节
压缩后运行效果
参考来源:
https://www.huangyunkun.com/2020/05/06/cargo-rust-output-size/
https://www.liqucn.com/rj/74253.shtml upx下载网站
https://github.com/DaviRain-Su/rust-no-std-source //嵌入式可以使用#![no_std]减少文件体积
本博客文章绝大多数为原创,少量为转载,代码经过测试验证,如果有疑问直接留言或者私信我。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。