Can I set Cargo project's default features depending on the platform?

Viewed 1406

Is it possible to make the list of default features platform dependent in your Cargo.toml? I'd like to use features to select platform-dependent dependencies.

I'd imagine something like this:

[features]
# on Unix
default = ["feature-a"]
# not on Unix
default = ["feature-b"]

feature-a = ["dep-a"]
feature-b = ["dep-b"]

[dependencies]
dep-a = { version = "*", optional = true }
dep-b = { version = "*", optional = true }

I've tried:

  • Using [target.'cfg(unix)'.features] does not work, it is ignored:

    [target.'cfg(unix)'.features]
    default = ["feature-a"]
    # -- snip --
    
  • Using a build.rs script to enable features based on cfg conditions only partially works. Dependency resolution is done before running build.rs, so this won't import optional dependencies for features enabled in it. This example won't import dep-a:

    fn main() {
        #[cfg(unix)]
        println!("cargo:rustc-cfg=feature=\"feature-a\"");
        // -- snip --
    }
    

Can this be achieved within Rust itself, without external scripts?

1 Answers

You can specify different features under each cfg. There is no support of cfg for root section features. So you can reach your goal but in a different way.

You can have different dependencies with different set of features.

For example:

[target.'cfg( target_os = "android" )'.dependencies]
some_dep = { version = "0.3.0", features = [ "feature1" ] }

[target.'cfg( target_os = "ios" )'.dependencies]
some_dep = { version = "0.3.0", features = [ "feature2" ] }

Official documentation.

Related