Rust嵌入式教程(6)- 优化固件体积

B站视频教程链接:https://www.bilibili.com/video/BV1pb4y1A72W

安装工具

cargo-binutil

https://github.com/rust-embedded/cargo-binutils

1
2
cargo install cargo-binutils
rustup component add llvm-tools

cargo-bloat

1
cargo install cargo-bloat

使用 --release

默认cargo build是debug模式,debug信息会占用大量固件内容。打包生产需要使用 --release

1
cargo build --release

下面的所有命令,都可以加上 --release。如果不加,默认都是对debug模式下的固件执行相关命令。

查看固件大小

默认生成的固件是 elf 文件,其大小不能真实地反映固件大小。

查看固件/text/data/bss段的大小

1
cargo size

查看每个section的大小

1
2
3
4
cargo size -- -A

# 十六进制展示
cargo size -- -A -x

配置 Cargo.toml

文档:https://doc.rust-lang.org/cargo/reference/profiles.html#profiles

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
[profile.dev]
codegen-units = 1      # better optimizations
debug = true
opt-level = 1
overflow-checks = true
lto = false
panic = 'unwind'

[profile.release]
codegen-units = 1       # better optimizations
debug = true            # no overhead for bare-metal
opt-level = "z"         # optimize for binary size
opt-level = "s"         # 
overflow-checks = false
lto = "fat

分析固件大小

1
cargo bloat --release

使用 nm 分析

1
cargo nm --release -- --print-size --size-sort

编译生成 .bin 文件

下面的命令会自动重新编译工程,并且生成 .bin 文件

1
cargo objcopy --release -- -O binary rust-embedded-demo.bin

tasks.json里面配置如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
    "label": "build .bin firmware",
    "type": "shell",
    "command": "cargo objcopy --release -- -O binary \"${workspaceFolder}/target/release/rust-embedded-demo.bin\"",
    "problemMatcher": [
        "$rustc"
    ],
    "group": {
        "kind": "build",
    },
},

注意:bin 无法调试。最好 elf/bin 文件都生成出来

updatedupdated2024-05-102024-05-10