3

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.

4
  • 1
    You can check out the documentation for it. Commented Sep 27, 2016 at 23:43
  • I read this page, but didn't see examples of this. Commented Sep 28, 2016 at 1:14
  • It's under the comment # A list of all of the optional dependencies. Commented Sep 28, 2016 at 13:39
  • @Shepmaster, yes, I read this. The difference is my dependency is local, instead of an optional external crate, the difference in syntax threw me. Updated the question to make this clear. Commented Sep 28, 2016 at 20:43

2 Answers 2

6

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.