cargo: Cannot declare different version of dependencies in mutually exclusive targets

Maintainer’s update

  • This is fixed for registry dependencies but not git dependencies

That’s a mouthful, but here’s an example:

[target.'cfg(not(target_os = "linux"))'.dependencies]
nix = "0.5.0"

[target.'cfg(target_os = "linux")'.dependencies]
nix = "0.4.3"

Unfortunately, right now this isn’t allowed as it’s considered a duplicate declaration per #2491.

The use case for this is that FreeBSD requires a newer version of nix to work. However, Linuxes with glibc 2.5 require an older version of nix.

My very ugly workaround is to fork nix and rename it. Then I can use cfg to import the correct crate in the source.

About this issue

  • Original URL
  • State: open
  • Created 10 years ago
  • Reactions: 5
  • Comments: 16 (9 by maintainers)

Commits related to this issue

Most upvoted comments

I have an issue that is very similar to this. Essentially, when you run cargo check or cargo build, cargo will compile dependencies for all the targets provided. For example, I have a case like this:

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio       ={ version="1", features=["rt", "rt-multi-thread", "macros", "net", "io-std", "fs"] }
# snip

[target.'cfg(target_arch = "wasm32")'.dependencies]
# No use of `tokio`
# snip

There are, of course, other dependencies that change between the wasm32 and non-wasm32 targets, but what I find is that cargo check builds tokio for wasm32.

This is happening given that distinct portions of code are gated with:

#[cfg(not(target_arch = "wasm32"))] pub mod my_mod;
#[cfg(target_arch = "wasm32")] pub mod my_wasm_mod;

Now, I can resolve this by compiling targets separately:

cargo check --target wasm32-unknown-unknown
cargo check --target aarch64-apple-ios

But this leaves a lot to be desired. It’s not really very easy to then have rust-analyzer use cargo check as we need to adjust its settings to only focus on a single target at a time. We also cannot build both targets with a single command.

What would be great is, like with features as well, we can have cargo check and cargo build only compile the features and dependencies necessary for the specific target in mind.