site  contact  subhomenews

Rust Hello World reduced to 31KB

September 26, 2022 — BarryK

A criticism that I have of Rust is that it creates very large binaries. Yes, there are websites that explain how to reduce the size, but have to go through a lot of steps.

This evening I was looking at this site, and compiled the first example:

..."Hello World!" was 315KB after stripping. Actually, that is better than last time I tried it. But, if I am going to write lots of utility programs in Rust, then they will need to be smaller.

Nim "Hello World!" binary is 19KB, with some simple optimizations. Create file 'nim.cfg' in same folder as the 'hello.nim', with this content:


Then compile and strip:

# nim c hello.nim
# strip hello

So the question is, can we, without too much difficulty, bring the Rust Hello World down to a comparable size? I found this site: explains a series of steps to progressively reduce the size. The optimizations down to "Abort on panic" requires a configuration file 'Cargo.toml' with this in it:

name = "min-sized-rust"
version = "0.1.0"
authors = ["johnthagen <>"]
license-file = "LICENSE.txt"


opt-level = "z" # Optimize for size.
lto = true # Enable Link Time Optimization
codegen-units = 1 # Reduce number of codegen units to increase optimizations.
panic = "abort" # Abort on panic
strip = true # Automatically strip symbols from the binary.

...disappointing though, Hello World! became 271KB, still rather large.

The next two sections "Optimize libstd with build-std" and "Remove panic String Formatting with panic_immediate_abort" reduce the binary to 31KB.

Beyond that, looks like it is compromising what Rust is all about, so went no further. 31KB is acceptable.

The execution line that produced the 31KB binary:

# cargo +nightly build -Z build-std=std,panic_abort -Z build-std-features=panic_immediate_abort --target x86_64-unknown-linux-gnu --release
...which is not too onerous. If compiling apps can be setup with these optimizations, then it does increase the attractiveness of Rust as a systems-programming language.     

Tags: easy