Why does a Rust `#![no_std]` firmware binary need a `#[panic_handler]` and `#![no_main]`, while a `#![no_std]` library needs neither?
answer
- std used to supply both
- exactly one per crate graph
- fn(&PanicInfo) -> !
- no generated main symbol
- libraries are not linked yet
basics
~20 sWithout std, nothing handles panics or calls fn main. The final binary supplies exactly one #[panic_handler] fn(&PanicInfo) -> ! and uses #![no_main] so a runtime crate's entry function starts it. A library is never linked alone, so it leaves both to the binary.
solid answer
~50 sTwo pieces of a normal program come from `std`. The panic handler: `std` decides whether a panic unwinds or aborts. Without it, the Reference requires that linking a `no_std` binary, dylib, cdylib or staticlib supply its own `#[panic_handler] fn(&PanicInfo) -> !`, exactly one in the whole dependency graph; otherwise rustc reports "`#[panic_handler]` function required, but not found", and two of them give E0152. The entry point: a `std` binary's `fn main` is called by a `main` symbol that std's runtime generates, so `no_std` with a plain `fn main` fails with "using `fn main` requires the standard library". `#![no_main]` stops rustc emitting that symbol, and a runtime crate such as cortex-m-rt supplies the reset path and calls your `#[entry]` function. An rlib library is never linked on its own, so it needs neither and should define neither.
code
rust · 32 lines#![no_std]
#![no_main]
use core::panic::PanicInfo;
use cortex_m_rt::entry;
fn crc16_ccitt(data: &[u8]) -> u16 {
let mut crc: u16 = 0xFFFF;
for &byte in data {
crc ^= (byte as u16) << 8;
for _ in 0..8 {
crc = if crc & 0x8000 != 0 { (crc << 1) ^ 0x1021 } else { crc << 1 };
}
}
crc
}
#[entry]
fn main() -> ! {
let frame = [0x31u8, 0x32, 0x33];
let _crc = crc16_ccitt(&frame);
loop {
cortex_m::asm::wfi();
}
}
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {
cortex_m::asm::bkpt();
}
}go deeper
Remember the two replacements a no_std binary makes: one panic handler with signature fn(&PanicInfo) -> !, and #![no_main] so a runtime crate's entry function starts the program.
Explain why both belong to the final binary and not to libraries, and quote what rustc reports when the handler is missing or defined twice.
Design the panic handler for production firmware: what it records from PanicInfo, how it halts or resets safely, and why the target's abort strategy matters.
Decide where a team's panic and entry policy lives, such as one handler crate shared by every board, so that libraries stay neutral and every binary behaves the same.
## What `std` was doing for you An ordinary Rust binary gets two things from `std` without asking: - **A panic handler.** When `panic!` fires, an index is out of bounds, or `unwrap` meets `None`, `std` either unwinds the stack or aborts the process, depending on the panic strategy. - **An entry point.** Your `fn main` is not what the operating system calls. `std`'s runtime emits the real `main` symbol, sets up the program (the embedded book lists stack-overflow protection, command-line arguments and the main thread), then calls your function. `#![no_std]` removes both, and a firmware binary has to replace them. ## The panic handler The Reference defines the rules: 1. The `#[panic_handler]` attribute goes on a function with the signature `fn(&PanicInfo) -> !`, with `core::panic::PanicInfo`. It may never return. 2. There must be **a single** panic handler in the dependency graph. 3. Linking a `no_std` **binary, dylib, cdylib or staticlib** requires one. The two failure messages from rustc 1.99.1: | situation | what rustc prints | |---|---| | no handler anywhere in the graph | "`#[panic_handler]` function required, but not found" | | two handlers, say one in a dependency and one in the binary | E0152, "found duplicate lang item `panic_impl`" | What a handler typically does on a microcontroller: record where the panic happened, then stop. `PanicInfo::location()` gives the file and line (the docs say it currently always returns `Some`), and `PanicInfo::message()` returns a value that implements `Display`, so a handler with a serial port can `write!` it. `message().as_str()` returns `Some` for a literal message such as `panic!("bad frame")` and usually `None` when the message has placeholders. Then the handler disables interrupts and loops, or triggers a breakpoint or a reset. Some projects keep the handler in a tiny crate that does nothing else and pull it in with `use that_crate as _;`. That works precisely because of rule 2: it is the one definition in the graph, and the binary must not define another. ## A handler fit for production 1. **Keep it short and unable to panic again**: no `unwrap`, no indexing that can fail, nothing that waits on a peripheral that may itself be broken. 2. **Record the evidence**: the file and line from `location()`, perhaps the message, written to RAM that the next boot inspects or to a debug probe's log. 3. **Make the device safe**: disable interrupts (`cortex_m::interrupt::disable()` on Cortex-M) and put outputs such as motor drivers or heaters into their safe state. 4. **Then stop or restart**: an endless loop or `cortex_m::asm::bkpt()` for a developer with a debugger attached, a reset for units in the field. Formatting `message()` pulls `core::fmt` machinery into the image, which costs flash on small parts, so some teams record only the location. ## Why a library needs neither A library crate compiles to an rlib that is never linked by itself. The handler and the entry point are decisions about the **final program**, so they belong to the binary: - A `no_std` library that panics (an `unwrap`, an indexing operation) is fine; its panics go to whatever handler the binary chooses. - A library that **defines** a handler takes that choice away from every user, and any user with their own handler gets E0152. The same split applies to `#[global_allocator]`: libraries use `alloc`, the binary picks the allocator. ## The entry point and `#![no_main]` Keep `#![no_std]` with a plain `fn main()` and build for thumbv7em-none-eabihf, and rustc stops with "using `fn main` requires the standard library", with the help line suggesting `#![no_main]`. The Reference says `no_main` disables emitting the `main` symbol for an executable. Something else must then be the entry: - On Cortex-M, the cortex-m-rt crate places the reset handler in the vector table, initialises RAM and calls the function marked `#[entry]`, which has the type `fn() -> !`. The HAL material covers that crate and its linker script. - A kernel or bootloader may export its own entry symbol with `#[unsafe(no_mangle)]` (the 2024 spelling of `no_mangle`). ## The panic strategy on bare-metal targets `rustc --print cfg --target thumbv7em-none-eabihf` reports `panic="abort"`: that target is built to abort, so a panic goes straight to your handler and no unwinding machinery is involved. Build a `no_std` binary for the host instead, where the default is `panic="unwind"`, and rustc 1.99.1 refuses with "unwinding panics are not supported without std". Panics in `std` programs (unwinding, `catch_unwind`, hooks) are the error-handling material's subject.
- In a `no_std` Rust binary, what can a `#[panic_handler]` read from its `PanicInfo` argument?`location()` returns the file, line and column of the panic and currently always returns `Some`. `message()` returns a `PanicMessage` that implements `Display`, so it can be written to a UART with `write!`; its `as_str()` is `Some` for a literal message. `payload()` exists only for compatibility, is deprecated and never returns anything useful.
- Why does building a Rust `no_std` binary for the host fail with "unwinding panics are not supported without std"?The host target's default panic strategy is unwind, and the precompiled `core` is built that way, but unwinding needs support code that comes with `std`. Bare-metal targets such as thumbv7em-none-eabihf default to `panic="abort"`, so a panic goes straight to the handler and the build links.
- Should a published `no_std` Rust driver crate define its own `#[panic_handler]`?No. Only one handler may exist in the dependency graph, so a library that defines one collides, with E0152, with every binary that has its own, and it takes a final-program decision away from the user. The library just lets panics happen; the binary chooses to halt, log or reset.
- Defining a `#[panic_handler]` in a reusable `no_std` library crate.
- Thinking `#![no_main]` means the program has no entry point at all.
- Giving the panic handler a return type of `()` so it can resume.
- Expecting a `no_std` library to fail to build without a panic handler.
- Believing `panic = "abort"` alone removes the need for a panic handler.