问题
Given this small library which uses local crates in subdirectories, how would I make one of the dependencies optional, depending on if a feature is enabled?
[package]
name = "image_load"
description = "Small wrapper for image reading API's."
version = "0.1.0"
[features]
default = ["use_png"]
[dependencies]
[dependencies.image_load_ppm]
path = "ppm"
# How to make this build _only_ when 'use_png' feature is enabled?
[dependencies.image_load_png]
path = "png"
While I read the documentation, this shows how to have optional external dependencies. In the example above I'm using a local subdirectory, which I want to build, or not - based on a feature.
How can I make image_load_png
only build when the use_png
feature is enabled.
回答1:
This can be done by adding the following:
[package]
name = "image_load"
version = "0.1.0"
description = "Small wrapper for image reading API's."
[features]
default = ["use_png"]
use_png = ["image_load_png"] # <-- new line
[dependencies]
[dependencies.image_load_ppm]
path = "ppm"
[dependencies.image_load_png]
path = "png"
optional = true # <-- new line
Using the crate can be optional.
e.g.:
#[cfg(feature = "use_png")] // <-- new line
extern crate image_load_png;
回答2:
Dependencies marked as optional double as features. However, if you want a feature with a different name, you'll have to define it manually.
For instance, if you mark the dependency image_load_png
as optional, then image_load_png
will only be compiled if the image_load_png
feature is enabled. You can test for the feature being enabled in the Rust code just like any other feature.
[dependencies.image_load_png]
path = "png"
optional = true
来源:https://stackoverflow.com/questions/39735660/how-to-make-a-local-dependency-depend-on-a-feature-in-cargo