Search code examples
rustrust-cargo

Using rust features as a build flag


I'm trying to use the features of a Cargo.toml file to conditionally set a property at build time. I do this so that I can have some slight differences for the build intended for integration testing.

#[cfg(feature = "inttest")]
const INFO_BYTES_SIZE: u32 = 28500;

#[cfg(not(feature = "inttest"))]
const INFO_BYTES_SIZE: u32 = 2000;

pretty simple right? If the inttest feature is enabled then MAX_SWAP_INFO_BYTES_SIZE becomes 28500.

all the packages .toml files have the same feature and list the dependency like so


[features]
default = []  # Empty default features
inttest = []

[dependencies]
common_code = { path = "../common", features = []}

when i build cargo build --target wasm32-unknown-unknown --target-dir $1/target --release --locked --features inttest -p $1

the feature doesn't get turned on and i still see the INFO_BYTES_SIZE as 2000.

Any ideas on why?

if i set the feature like so

common_code = { path = "../common", features = ["inttest"]}

then it does work, but now production has the wrong value and it's always set to 28500


Solution

  • Features are defined per-crate. Here, both package and common_code have a feature named inttest, but they are not the same feature; they just happen to be named the same. Enabling package/inttest will not automatically enable common_code/inttest.

    If you want enabling package/inttest to also enable common_code/inttest, you need to explicitly state the feature dependency:

    [features]
    default = []
    inttest = ["common_code/inttest"]
    
    [dependencies]
    common_code = { path = "../common" }
    

    See The Cargo Book.