Compressing static lib in Rust

Converti le tout en static lib.

Currently I'm learning Rust through their official book, the purpose being that I'm building a hybrid monolithic kernel in C and Rust, each of them bringing their own stuff to the table.

In my case I'm really limited by constraints, and my goal is to have a very lightweight binary. On my first compilation, I noticed that the binary size was still quite heavy (~13M) and so this was the first time I found something to criticize about this magnificent language, even if it's the price of a solid abstraction. For the little anecdote, Linux 0.01 was around ~60 KB, a kernel must be reasonably small, it shouldn't consume the very resources it's supposed to manage.

So I tried to build a basic project, and the binaries are extremely heavy out of the box. This is due to static linking, monomorphization (to put it short: if you have a function that accepts generic types and you call it with 10 different types, Rust won't do a kind of type erasure like Java it will duplicate your code at compile time), and several other reasons that can quickly make your program bloat.

And as every problem has a solution, we have this profile as an optimized configuration:

[profile.release] opt-level = "z" # optimize for size (not speed) lto = true # link-Time Optimization codegen-units = 1 # single compilation thread = better inlining/LTO panic = "abort" # no stack unwinding = removes panic handling code strip = true # strip all debug symbols

Ideally, we should also avoid all costly abstractions such as format!, Vec, Box, println!, and core::fmt.

And to adapt to the kernel development environment, it's important to include these inner attributes:

#![no_std]: Rust's standard library assumes you're running on a complete OS. The dependencies are not adequate for kernel development. We are the OS.

#![no_main]: Disables the standard entry point and the startup code generated by Rust. We already handle the starting point ourselves.

With these optimizations, we are now down to ~13 KB. :) !

Last updated