1

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?

Curunir
  • 1,186
  • 2
  • 13
  • 30

1 Answers1

4

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
}
Miiao
  • 751
  • 1
  • 8
  • Thanks for the explanation! btw. One also has to add the `eh_personality` language item. – Curunir Feb 02 '23 at 08:20
  • @curunir, it's not supposed to require an `eh_personality` of your target or cargo.toml declare aborting on panic. You can make a dummy function though ``` #[lang = "eh_personality"] fn ep() {} ``` This will generate one or two dummy symbols in binary. Not the best option, but definitely not the worst. – Miiao Feb 02 '23 at 18:12
  • Strangely enough I had panic = "abort" on both the release and dev profile but it kept complaining. – Curunir Feb 03 '23 at 07:47