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/


use core::panic::PanicInfo;

fn panic(_info: &PanicInfo) -> ! {
    loop {}

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

In your Cargo.toml:

panic = "abort"

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)

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: