Is it possible for a cargo feature to remove a dependency?

2.3k Views Asked by At

I am looking to add the possibility to add the possibility of using my crate without the standard library. Some of the core functionality does depend on floating-point functions, which in no-std mode would need to be provided by libm.

The usual way I've seen no-std setup is to have a feature called "std" that enables the standard library, but in this case I would want the feature to remove the libm dependency. I could call the "additional" feature "no-std", but that then leads to the issue that I have certain features that would be difficult to implement in no-std mode, so I'd want them to depend on std being enabled.

Is it possible for cargo to specify an optional dependency that is present only when a feature is not enabled?

1

There are 1 best solutions below

0
On

No, Cargo features cannot remove dependencies.

Dependencies can be specified with optional = true which are not included unless enabled via a feature, but the mechanism cannot disable a dependency. See optional dependencies in the Cargo Book for how that works. Cargo features are generally designed to be additive and thus adding one should not generally remove functionality.

Your use-case is a bit out of the norm so your best route is to follow what @Masklinn suggested and create "mutually exclusive" features (not officially supported):

  • have a "std" and "libm" features such that the "libm" feature enables the libm dependency

    [features]
    default = ["std"]
    std = []
    libm = ["dep:libm"]
    
    [dependencies]
    libm = { version = "*", optional = true }
    
  • trigger a compiler error if both are enabled:

    #[cfg(all(feature = "std", feature = "libm"))]
    compile_error!("features \"std\" and \"libm\" cannot be enabled simultaneously")
    

Still not ideal since, again, Cargo features are generally designed to be additive and due to feature-unification both may be enabled unintentionally but at least the above compiler error message should help.