rust-lang / rust-lang/rust

cargo test build error on combined crate types "lib" and "cdylib" in #[no_std] context; ignores #[cfg(not(test))]

Open
#151,083 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-discussion needs-triage
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Have a crate that combines these properties:

  1. #[no_std], which requires panic = 'abort'
  2. crate type = ["lib", "cdylib"]

#[no_std] requires own #[panic_handler]. Yet for testing, panic must be unwind. This requires std. This requires to omit own panic handler. So they must be built conditionally.

Cargo.toml:

[package]
name = "testbuilderror"
[lib]
crate-type = ["lib","cdylib"]
[profile.dev]
panic = 'abort'
[profile.test]
panic = 'unwind'

src/lib.rs

#![cfg_attr(not(test), no_std)]     // no_std only if not testing
#[cfg(not(test))]                   // own panic handler only if not testing
#[allow(unsafe_code, reason = "panic_handler")]
#[panic_handler]
unsafe fn panic(_pi: &core::panic::PanicInfo<'_>) -> ! { todo!() }

Expected result:

  • cargo build: successful build
  • cargo test: successful build and test run

Actual result:

  • cargo build: successful build;
  • 💥 cargo test -> error: unwinding panics are not supported without std

Works if crate type is either lib or cdylib. Fails only if both are used. Condition not(test) seems not regarded by compiler then. I don't think crate type should have any influence on how test flag is regarded by compiler?

Same results on Rust 1.81, 1.92 and Nightly 1.94. Ubuntu Linux 25.10; x86-64.

Rationale: I work on a #[nostd] cdylib. Originally was a single crate. Then split into multiple crates in a workspace. This required to add crate type lib to enable modules to access modules of their workspace sibling crates.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the issue with the provided Cargo.toml and src/lib.rs, comparing cargo build and cargo test when crate-type is ["lib", "cdylib"] versus each type alone. Start by tracing how the test configuration and crate types are handled; done means cargo test respects #[cfg(not(test))], builds successfully, and runs the test suite.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
build-system, compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.