Is it possible to enable certain features for a dependency only for debug builds?

I'm working on a game using Bevy, and a recommendation is to enable the dynamic_linking feature to speed up compilation during development, but it's recommended to disable it for release builds, because then you'll have to distribute libbevy_dylib with your game binary.

I don't want to have to manually unset dynamic_linking every time I want to build a release build, so is it possible to only have this flag enabled for debug builds?

1 Like

Just list bevy under [dev-dependencies] (in addition to the entry under [dependencies]) and enable the feature there:

[dev-dependencies]
bevy = { version = "0.12.0", features = ["dynamic_linking"] }

You will have to make sure that the two bevy dependencies always have compatible versions going forward, though.

1 Like

Specifying Dependencies - The Cargo Book

Does this work?

[target.'cfg(debug_assertions)'.dependencies]
bevy = { version = "0.12.0", features = ["dynamic_linking"] }

Alternatively, you could make a feature for it. This is useful if you want your code optimized but still want to use bevy's dynamic linking.

This isn't how dev-dependencies works. Those are dependencies that are only enabled if you are compiling tests, examples, or benchmarks. You'd need to use an example for development purposes instead of the regular main.rs.

1 Like

Does this work?

Sadly, no:

warning: Found `debug_assertions` in `target.'cfg(...)'.dependencies`. This value is not supported for selecting dependencies and will not work as expected. To learn more visit https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#platform-specific-dependencies
1 Like

Well in that case, I think a feature would be the least effort.

1 Like

Thanks. Do you think I should also make a feature request for this?

It looks like the problem is that debug_assertions is set by default, and it isn't unset until the profile table is read, which happens independently from these cfg expressions.
target.'cfg(debug_assertions)'.dependencies doesn't work as expected · Issue #7634 · rust-lang/cargo · GitHub
[target.'cfg(all(target_arch="x86_64", not(debug_assertions)))'] in .cargo/config doesn't seem to work · Issue #5777 · rust-lang/cargo · GitHub

It seems like everything in Cargo.toml should be able to know which profile is selected, without any info about the contents of the profile. In this case, that's equivalent to knowing if debug_assertions is set.

However, I just remembered that aliases exist, which should do what you probably actually want, which is to have a short command.

# .cargo/config.toml
[alias]
bd = "build --features bevy/dynamic_linking"
rd = "run --features bevy/dynamic_linking"
bdr = "bd --release"
rdr = "rd --release"
3 Likes