In workspace, cargo in check each package succeeds but fails in workspace root with features

I have two binaries and a library used by both in a workspace, and all of them are in no_std.
A binary has global_allocator, and the other doesn't. So, the library has "alloc" feature to handle both cases.

Then when I try to run cargo check in the workspace root, it fails with error

error: no global allocator found but one is required; ...

error: could not compile `<no global alloc one>` (bin "...") due to 1 previous error

but cargo check -p <each binary> succeeds.

How can I resolve this problem?

Is your workspace's Cargo.toml set to edition 2021 or to use resolver=2?

Yes. Both are set.

It's probably not funky feature unification then.

When you use the -p option,[1] this has the effect that only features in that package’s dependencies are enabled. When you don't specify a package, dependencies are compiled with the union of features required by all packages being built.

So, presumably, compiling that binary doesn't succeed when the library’s alloc feature is enabled. Assuming that’s expected and not a bug, then a way to resolve this issue is to set workspace.default-members to exclude either the “no global alloc one” or the other binary from the default set of packages, since they can't be compiled together. That’ll keep cargo check usable, at the price of not checking 100% of your code.

Of course, then you'll need to remember to check/test the excluded package separately. This is a good use for the xtask pattern to add a little “scripting” to test your workspace all the ways it needs testing. (There's no way to do it in a single cargo command — but that's also true in general of any situation where you have features to test enabling and disabling.)


  1. Note that -p selects a package, not a target, though I think that is not relevant in this case. ↩︎

1 Like

Thank you. I will use some scripts.

By the way, is it better not to use workspace in these situations?

Not particularly. Using a workspace gets you a shared build cache for all your dependencies not affected by this feature, and you'd still have to run the same number of commands.

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.