想使用rust进行嵌入式开发,又听说bin包会很大,到底能压缩到多小呢,手动测试一下。
1 下载官网的嵌入式例程
cargo install cargo-generate
cargo generate --git https://github.com/rust-embedded/cortex-m-quickstart
rustup target add thumbv7m-none-eabi
2 工程中就是加个简单的打印
use cortex_m::asm;
use cortex_m_rt::entry;
use cortex_m_semihosting::hprintln;
#[entry]
fn main() -> ! {
asm::nop(); // To not have main optimize to abort in release mode, remove when you add code
hprintln!("Hello, world!").unwrap();
loop {
asm::nop(); // your code goes here
}
}
cargo已经有部分的优化了
[profile.release]
codegen-units = 1 # better optimizations
debug = true # symbols are nice and they don't increase the size on Flash
lto = true # better optimizations
直接运行release编译,看看大小54k,有点大
加上strip = true 去掉符号表看看
[profile.release]
codegen-units = 1 # better optimizations
debug = true # symbols are nice and they don't increase the size on Flash
lto = true # better optimizations
strip = true
opt-level = "z"
panic = "abort"
这次变的很小了2.2k,比c的应该大不了多少,效果还是可以的。
3 有个问题,使用官网的nrf-hal/examples/hello-world,编译出来的bin文件有129k
用hexyl看了下二进制,发现中间有两段地址(0xd0~0x10000),(0x109c0~0x20000)里面全是0,
这两段就占用了将近120k的空间,实际程序也就几k左右,估计是链接器对齐之类的造成的,编译之前设置链接参数
export RUSTFLAGS="-C link-arg=--nmagic -C link-arg=-Tlink.x"
再编译结果只有2.7k,很小了。
4 结论
使用rust开发嵌入式, 在优化状态下,二进制不会大多少,是个可行的方式,目前限制的主要原因可能是嵌入式生态还不完善吧。