DEV Community

ender minyard
ender minyard

Posted on

Rust no_std template

There are many in-depth tutorials that explain how to write a #![no_std] binary. This is just a simple, reusable bare-bones template that works for me.

In your src/main.rs:

#![no_std]
#![no_main]

use core::panic::PanicInfo;

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

#[no_mangle]
pub extern "C" fn _start() -> ! {
    loop {}
}
Enter fullscreen mode Exit fullscreen mode

In your Cargo.toml:

[profile.dev]
panic = "abort"

[profile.release]
panic = "abort"
Enter fullscreen mode Exit fullscreen mode

Instead of simply running cargo build to generate a binary like usual, you need to jump through some hoops to generate a binary.

If you are compiling this binary for Linux, you can run:

cargo rustc -- -C link-arg=-nostartfiles

For Windows:

cargo rustc -- -C link-args="/ENTRY:_start /SUBSYSTEM:console"

For macOS:

cargo rustc -- -C link-args="-e __start -static -nostartfiles"


All of this is useful if you plan on running the resulting binary on bare metal. If you're compiling Rust to WebAssembly, none of this is necessary - simply not using the std library is enough for that use case.

If you're targeting the WebAssembly System Interface, it's more simple and you can even use Rust's std library for that use case.

Top comments (1)

Collapse
 
nicholassterling profile image
Nicholas Sterling

Thanks! And here is a Github project that demonstrates how to set up the CI so that it checks that the crate actually builds without std:

github.com/KodrAus/rust-no-std