A Rust crc16 library with `#![cfg_attr(not(feature = "std"), no_std)]` builds with `--no-default-features` on a laptop yet fails for a thumbv7em-none-eabihf user; why, and how do you catch it?
answer
- the host sysroot has std
- a dependency is std-only
- E0463 names the culprit
- build for a target without std
- core::error::Error since 1.81
basics
~20 sThe laptop's sysroot has std, so a dependency that is not no_std links it silently. A target without std fails with E0463 naming that dependency, so CI must build the no-std feature sets for such a target.
solid answer
~50 s`--no-default-features` on the host proves only that the crate's own code avoids `std`: an ungated `String` fails there with E0425 and `format!` with "cannot find macro `format` in this scope". It cannot prove the dependency graph is clean, because the host target ships `std` and any dependency that does not declare `#![no_std]` simply links it. On thumbv7em-none-eabihf there is no `std` to find, so rustc stops with E0463, "can't find crate for `std`", and a note naming the dependency. The fix is to depend on such crates with their default features off and forward this crate's `std` feature to theirs, and the guard is a CI job that builds `--no-default-features` (and `--features alloc`) for a target without `std`. Two related habits: implement `core::error::Error`, stable since Rust 1.81, instead of gating `std::error::Error`, and write `extern crate std;` in test modules, because the test harness runs on the host and proves nothing about `no_std`.
code
rust · 48 lines#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "alloc")]
extern crate alloc;
#[derive(Debug, PartialEq)]
pub struct Mismatch { pub expected: u16, pub found: u16 }
impl core::fmt::Display for Mismatch {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "crc {:#06x}, expected {:#06x}", self.found, self.expected)
}
}
// core::error::Error (stable since 1.81): no std feature needed.
impl core::error::Error for Mismatch {}
pub fn checksum(data: &[u8]) -> u16 {
data.iter().fold(0xFFFF, |crc, &b| {
(0..8).fold(crc ^ (u16::from(b) << 8), |c, _| {
if c & 0x8000 != 0 { (c << 1) ^ 0x1021 } else { c << 1 }
})
})
}
#[cfg(feature = "alloc")]
pub fn with_crc(payload: &[u8]) -> alloc::vec::Vec<u8> {
let mut frame = payload.to_vec();
frame.extend_from_slice(&checksum(payload).to_be_bytes());
frame
}
#[cfg(feature = "std")]
pub fn checksum_reader(mut r: impl std::io::Read) -> std::io::Result<u16> {
let mut buf = std::vec::Vec::new();
r.read_to_end(&mut buf)?;
Ok(checksum(&buf))
}
#[cfg(test)]
mod tests {
extern crate std; // the harness links std; a no_std crate still names it
#[test]
fn check_value() {
assert_eq!(super::checksum(b"123456789"), 0x29B1);
std::println!("{}", super::Mismatch { expected: 0x29B1, found: 0 });
}
}go deeper
Know that a Cargo feature named std can turn #![no_std] on or off, and that the board build, not the laptop build, is the real test.
Explain the two failure classes: ungated std-prelude use caught on the host, and a std-only dependency caught only on a target without std.
Read E0463's note to find the culprit dependency, fix its features, and add CI builds of each feature set for a no-std target.
Decide which feature sets the crate promises, whether the 1.81 MSRV for core::error::Error is acceptable, and how CI enforces the promise.
## The pattern and what it promises A library that serves both firmware and ordinary programs usually starts with: - `#![cfg_attr(not(feature = "std"), no_std)]` at the crate root: with the `std` Cargo feature off, the crate is `no_std`. - `#[cfg(feature = "alloc")] extern crate alloc;` for heap-backed APIs. - `#[cfg(feature = "std")]` on items that need the OS, such as a function taking `impl std::io::Read`. Declaring the `std` and `alloc` features, making `std` the default and keeping features additive is Cargo's features material. The promise to a firmware user is: with default features off, nothing in the build needs `std`. ## Why the laptop build passes `cargo build --no-default-features` on the host turns the attribute on, and it catches one class of mistake: 1. **Ungated use of the std prelude.** A helper returning `String` or calling `format!` without `#[cfg(feature = "alloc")]` fails on the host too: E0425 "cannot find type `String` in this scope" and "cannot find macro `format` in this scope". It cannot catch the other class: 2. **A dependency that needs `std`.** `#![no_std]` covers only this crate. The host target's sysroot contains `std`, so a dependency that never declared `#![no_std]`, or a no_std-capable one whose default `std` feature was left on, links it without complaint. ## Why the board build fails thumbv7em-none-eabihf has no `std` in its sysroot. The moment any crate in the graph requires it, rustc 1.99.1 prints E0463, "can't find crate for `std`", with two notes: the target "may not support the standard library", and "`std` is required by `helper` because it does not declare `#![no_std]`". That note names the culprit, often several crates down the graph. The repair depends on the dependency: - A crate that supports `no_std`: depend on it with default features off and forward your `std` feature to its `std` feature (Cargo's features material). - A crate that cannot: make it optional and enable it only from your `std` feature, or replace it. - Cargo unifies features across the graph, so one crate that enables a dependency's `std` turns it on for that dependency in the whole build; that is one more reason to test the exact feature sets firmware users build. ## Catching it in CI Install a target without `std` (adding targets and their linkers is Cargo's configuration material) and run, alongside the normal test job: | job | proves | |---|---| | `cargo test` | behaviour, on the host, with default features | | `cargo build --target thumbv7em-none-eabihf --no-default-features` | the core tier needs no `std` anywhere in the graph | | `cargo build --target thumbv7em-none-eabihf --no-default-features --features alloc` | the `alloc` tier needs an allocator but no `std` | A stricter alternative for the crate root, shown in the Cargo book: write `#![no_std]` unconditionally and `#[cfg(feature = "std")] extern crate std;`. The prelude is then `core`'s in every build, so an ungated `String` fails even in the default build, before CI. ## Reading the snippet - The `cfg_attr` line makes the crate `no_std` whenever the `std` feature is off. - `extern crate alloc;` is compiled only with the `alloc` feature, and so is `with_crc`, the one function that returns a `Vec`. - `checksum_reader` takes `impl std::io::Read` and exists only with `std`; it names `std::` explicitly because, with `std` on, the crate is an ordinary `std` crate. - `checksum` and the `Mismatch` error type are ungated: they are the core tier every user gets. - The test module writes `extern crate std;` so that its `std::println!` resolves in all three feature sets. ## Tests and error types - **Tests run on the host.** The test harness links `std`, so `cargo test --no-default-features` passes even for code that would break on a board. Inside a `no_std` crate, a test module that needs `std::println!` or `std::vec!` writes `extern crate std;`; without it, `std::` paths fail with E0433. - **Error types.** `core::error::Error` has been stable since Rust 1.81, so `impl core::error::Error for Mismatch {}` works in every feature set. Crates written for older compilers gated `impl std::error::Error` behind `std`, which left firmware users with an error type that did not implement the trait. Using the `core` path raises the crate's minimum supported Rust version to 1.81, a choice the MSRV policy owns.
- In a Rust library that is optionally `no_std`, what does writing `#![no_std]` unconditionally with `#[cfg(feature = "std")] extern crate std;` change?The prelude is `core`'s in every build, including the default one with `std` on. A helper that uses `String`, `Vec` or `format!` without an `alloc` gate then fails immediately, not only under `--no-default-features`. Items that need the OS name `std::` explicitly. The Cargo book shows this form when explaining why `std` should be a feature and not a `no_std` feature.
- Why can't a passing `cargo test --no-default-features` show that a Rust crate works without `std`?The test harness itself depends on `std` and runs on the host, whose sysroot has `std`, so a dependency that requires `std` links happily. The run shows the crate's logic is correct with those features off, not that the graph builds on a target without `std`; only a build for such a target shows that.
- Treating a host `--no-default-features` build as proof that a crate is no_std.
- Assuming `#![no_std]` on a crate also applies to its dependencies.
- Gating `impl std::error::Error` behind `std` on a crate that requires Rust 1.81.
- Adding a `no_std` feature that removes std instead of a `std` feature.
- Relying on `cargo test` alone to check the no_std feature set.
Assumes Rust 1.99 on edition 2024; core::error::Error is stable since 1.81, earlier compilers need the impl gated behind the std feature.