Feature transitivity?

I have a bin crate and a library crate together in a workspace
and the lib has a feature on it. bin depends on the lib.
when I run 'cargo build --features x' the library is not
transitively receiving this feature.
(this was after I moved the feature dependent code out of the bin
into the lib)
rust-by-example lists the regex library as demonstrating re-export of features but I don't for the life of me see it!
searching elsewhere has yielded nothing so I think this must be so basic as to not be an issue for anyone else.
sorry about the basicness but I'm at my wits end after days of searching/experimenting.

This section of the Cargo book describes how to enable features of dependencies:

https://doc.rust-lang.org/cargo/reference/features.html#dependency-features

If you want to hide the feature of your dependency (your lib crate) behind a feature of your binary crate, you could add something like this to the binary crate package's Cargo.toml:

[dependencies]
lib = "0.1.0"

[features]
x = ["lib/x"]

Then when you enable the x feature of your binary crate, it will also enable the x feature of your library crate.

2 Likes

'x=[lib/x]' is the first thing I did and it didn't work!
I'm basing my 'not working' on the fact that
(cd lib; cargo expand --features x)
shows a macro expansion after a #[cfg(x)]
while 'cargo build --features x' from workspace directory fails in a way that can only mean 'x' was not seen.

I must be doing something stupid. here's minimal setup:
./Cargo.toml:

[workspace]
resolver = "2"
# directories!
members = ["lib"]

[package]
name = "test"
authors = ["{{authors}}"]
version = "0.1.0"
edition = "2021"

[dependencies]
lib={path="lib"}

[features]
x=["lib/x"]

src/main.rs:

fn main(){
    lib::f();
}

lib/Cargo.toml:

[package]
name = "lib"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["rlib", "dylib"]

[dependencies]

[features]
x=[]

lib/src/lib.rs:

#[cfg(feature="x")]
mod g {
    fn h(){ println!("h ok") }
}

use g::*;

pub fn f(){ h() }

Your cfg macro isn't the right syntax to enable f when feature x is present:

- #[cfg(x)]
+ #[cfg(feature = "x")]
pub fn f(){ println!("ok") }
2 Likes

ah, I wrote a non-minimal example by missing that out.
corrected above.
in any case problem solved - the list of errors from compiler put the real error down the list and I didn't look at that far until now.
thanks!