Write! macro doesn't work in no_std

I've been following documentation and example on using write! macro in no_std environment as described here, but it doesn't seem to work.

I came up with the following solution based on provided example:

use core::fmt::Write;

pub fn main() -> ! {

    let mut stdout = QemuStdout {};
    write!(&mut stdout, "Hello World").unwrap();

    loop { }
}

struct QemuStdout;

impl Write for QemuStdout {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        for c in s.chars() {
            unsafe {
                core::ptr::write_volatile(0x3F201000 as *mut u8, c as u8);
            }
        }
        Ok(())
    }
}

Nothing happens in the above case. However, if I write message as

stdout.write_str("Hello World").unwrap();

then it gets displayed.
What am I doing wrong with write! macro?

Is there a different write! macro somewhere in your project that it might be calling instead of core::write?

If you run it through https://github.com/dtolnay/cargo-expand do you see the write! call being expanded into a write_fmt function call?

There's something wrong with your crate. I installed it and tried to cargo expand, but it says:

error[E0463]: can't find crate for `core`
  |
  = note: the `aarch64-unknown-none` target may not be installed

The project builds fine and there's no other write! macros in it.

It's running cargo +nightly rustc internally so you would need to make sure your target is available for the nightly toolchain. Does cargo +nightly rustc compile successfully?

Hmm. I use nightly toolchain.

    Updating crates.io index
  Downloaded compiler_builtins v0.1.26
  Downloaded 1 crate (134.9 KB) in 2.07s
   Compiling compiler_builtins v0.1.26
   Compiling core v0.0.0 (/home/me/rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/src/libcore)
   Compiling rustc-std-workspace-core v1.99.0 (/home/me/rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/src/tools/rustc-std-workspace-core)
   Compiling alloc v0.0.0 (/tmp/xargo.HoVbhxmuR0Oe)

but cargo +nightly rustc fails with the same error: target may not be installed.

And

$ rustup target add aarch64-unknown-none
error: toolchain 'nightly-x86_64-unknown-linux-gnu' does not contain component 'rust-std' for target 'aarch64-unknown-none'

Well, that's expected

Well, I found the error and it has nothing to do with macros. I was just setting up stack pointer incorrectly

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.