How to make a local dependency depend on a feature in Cargo?

三世轮回 提交于 2021-01-27 11:37:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!