In this lesson, you will learn how to shed the Rust standard library and configure your toolchain to build bare-metal or embedded applications.
Escaping the Standard Library
When you compile a standard Rust program, it automatically links against std, which provides high-level abstractions like Vec, String, and file I/O. These rely on an underlying Operating System. To work in environments without an OS—such as kernels or embedded microcontrollers—you must instruct the compiler to stop linking std and instead use core.
Step 1: The #![no_std] Attribute
The first step is adding #![no_std] to the top of your main.rs or lib.rs. This tells the compiler that your crate does not have access to the standard library. Immediately, you will notice that common types like println! or Box are no longer available.
Step 2: The Panic Handler
In a standard environment, the panic handler prints a message to stderr and terminates the process. Without std, you must define how the system reacts to a panic. You do this by creating a function marked with the #[panic_handler] attribute:
use core::panic::PanicInfo;
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {} // A simple infinite loop to halt execution
}
Step 3: Removing the Entry Point
Since std typically handles the complex setup required to call your main function (like setting up command-line arguments), you must disable the default entry point. By using the attribute #![no_main], you tell the linker not to look for the standard main entry point. You will likely need to provide your own using #[no_mangle] pub extern "C" fn main() -> !.
The Toolchain Perspective
To finalize this setup, ensure you have the target architecture installed via rustup target add <target-triple>. If you are cross-compiling, you may need a .cargo/config.toml file to specify the target architecture and linker flags, ensuring your binary is generated in a format (like an ELF or raw binary) that your execution environment expects.
Key Takeaway: By using #![no_std] and providing a custom #[panic_handler], you strip away OS dependencies, allowing Rust to execute directly on bare metal.