How to test code when #![no_std] is set

Hello Rust-Forum:

I tried to write a rust OS kernel that mimics the implementation of xv6. Here is the link to it:

To write the OS, I set the main.rs #![no_std] and set target in .cargo/config.

[build]
target = "riscv64imac-unknown-none-elf"

[target.riscv64imac-unknown-none-elf]
rustflags = ["-C", "link-arg=-Tlinker.ld"]

However, the setting also stop me from testing my code. The problem become worse as I write more and more code without test.
The test I created will complain errors like:

  = note: the `riscv64imac-unknown-none-elf` target may not support the standard library
  = note: `std` is required by `test_42` because it does not declare `#![no_std]`
  = help: consider building the standard library from source with `cargo build -Zbuild-std`

Is there any way that I can test part of my code while build them with no_std?

I don't know about risc-v, usually for no_std crate, I can simply declare the extern crate std where std is needed, either enabled by a cargo feature, or in tests. like such:

#![no_std]

#[cfg(feature = "std")]
fn this_function_depends_on_std() {
    extern crate std;
}

#[cfg(test)]
mod tests {
    extern crate std;
}

but the message you posted make me wonder whether you can do it for your target:

if indeed the std library is unavailable for the target, you might need to use custom test harness other than std and test crates. but this need nightly toolchain. see

I see.
Yes my target does not provide the std I think.
Will try your solution from phil-opp. Thanks.

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.