Rust no_std static lib panic_handler

1.6k Views Asked by At

I want to build a no_std static library with rust. I got the following:

[package]
name = "nostdlb"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["staticlib"]

[profile.dev]
panic = "abort"

[profile.release]
panic = "abort"

lib.rs:

#![no_std]

pub fn add(left: usize, right: usize) -> usize {
    left + right
}

Despite setting the panic behaviour for both dev and release to abort cargo gives the following error:

error: `#[panic_handler]` function required, but not found

error: could not compile `nostdlb` due to previous error

I thought the panic handler is only required when there is no stack unwinding provided by std?

1

There are 1 best solutions below

3
On BEST ANSWER

No, you need to write your own one. If you need just aborting, consider using the following one:

#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
    loop {}
}

I also highly recommend to unmangle the function and use C calling convention if you’re going to use this symbol somewhere (not import it the library as a crate, but link it manually):

#[no_mangle]
extern fn add(right: usize, left: usize) -> usize {
   right + left
}