How to use `alloc` use in `no_std`?

Hi All,
I tried to use alloc::format! in my no_std program without success. The compiler said can't find. The source is as following:

#[macro_use]
extern crate alloc;
...
fn main() -> ! {
    ....
    let st = format!(...);
    ....
}

I am using rustc v1.82.0.

Thank you,
Tuan

Could you please copy and paste the error message you get from running cargo check in your console?

Here you are !

error[E0463]: can't find crate for `alloc`
 --> src/main.rs:5:1
  |
5 | extern crate alloc;
  | ^^^^^^^^^^^^^^^^^^^ can't find crate

error: cannot find macro `format` in this scope
  --> src/main.rs:16:16
   |
16 |     let text = format!("Hello {}", "world!");
   |                ^^^^^^

For more information about this error, try `rustc --explain E0463`.
error: could not compile `test01` (bin "test01") due to 2 previous errors

and here is the complete source code :slight_smile:

#![no_std]
#![no_main]

#[macro_use]
extern crate alloc;

use esp_backtrace as _;
use esp_hal::{delay::Delay, prelude::*};

#[entry]
fn main() -> ! {
    #[allow(unused)]
    let peripherals = esp_hal::init(esp_hal::Config::default());
    let delay = Delay::new();

    let text = format!("Hello {}", "world!");
    loop {
    }
}

Thanks

How do you compile the code and for what target?

I compile it for esp32 by normal cargo build In fact I have that source code auto-generated from esp-rs/esp-template and just added lines for testing the alloc::format!.

Thanks

Did you make sure to enable alloc during the init prompts? Your Cargo.toml should have esp-alloc in the dependencies, and your code is missing the heap init code the template adds: esp-template/pre-script.rhai at main · esp-rs/esp-template · GitHub

You can then call init_heap in main (in the template, it's placed right after the peripherals and delay are created).

1 Like

Thank you very much. It works!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.