Search code examples
rustrust-cargorust-crates

Dependent crates with std/no_std variants


I have a crate A which has a std and a no_std variant. They are differentiated by a feature named "std" which is by default on:

[features]
default = ["std"]
std = []

Now I want to create a crate B which shall have the same differentiation between std and no_std AND it shall depend on A. Now if B has "std" set, I would like to use A with "std" set as well and if "std" is not set in B, I would like the dependency A to also not have the feature "std" set.

How can I achieve this? I thought maybe [target.'cfg(...)'] and defining two dependency variants of A based on the presence of the feature might help but the syntax does not allow feature as a key and it seems as if it will not happen at all: https://github.com/rust-lang/cargo/issues/8170.


Solution

  • As The Cargo Book documents under Dependency features:

    Features of dependencies can also be enabled in the [features] table. The syntax is "package-name/feature-name". For example:

    [dependencies]
    jpeg-decoder = { version = "0.1.20", default-features = false }
    
    [features]
    # Enables parallel processing support by enabling the "rayon" feature of jpeg-decoder.
    parallel = ["jpeg-decoder/rayon"]
    

    Therefore, in the Cargo.toml of your crate B:

    [dependencies]
    a = { version = "...", default-features = false }
    
    [features]
    default = ["std"]
    std = ["a/std"]