Avoiding rebuilds when doing `cargo build --package <x>`

Short version:

Is there a way to unify cargo features between different cargo build --package X invocations, so they don't have to rebuild dependencies?

Long version

I have a CI for a project with a lot of crates with various features, all in one cargo workspace. We're using Nix to build them all (crane to be specific).

I have build for various packages which comes down to building with:

cargo build --package <pkga>


cargo build --package <pkgb>

crane allows me to have intermediate builds, including builds that contain only the dependencies of the project compiled.

So what I'd like to have is:

  • build all project dependencies
  • build pkga, reusing already compiled dependencies
  • build pkgsa, reusing already compile depdencies

However when actually running it I've noticed that each build of a package recompiles the dependencies again.

I suspect this is due to a number of features in packages pkga and pkgb and packages they depend on. Depending which one I'm building, different sets will be enabled which causes cargo to rebuild things. (?)

Any ideas how would I avoid that?

1 Like

AIUI the only way to avoid rebuilding dependencies with different (but compatible) features is to build all the packages with the same cargo invocation.

1 Like

There are some strategies to reduce this problem:

  1. The “workspace hack”: define a special package which

    • every other workspace package depends on, and
    • depends on all the features anything in the workspace does.

    More explanation is in the docs of cargo-hakari, a tool to automate this. (Disclaimer: I haven't used or evaluated it, just heard of it.)

  2. You can issue a command to build only a specific target (e.g. cargo build --bin <binary-target-name>) without selecting a package.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.