Detecting [dependencies]

Is there any way to detect if a crate is being used in a [dependencies] vs being directly cargo builded?

I don’t know for sure, but the first thing I would try is to look for a difference in the compile time environment variables using env! or similar.

I had a look at the environment variables cargo sets for crates and found CARGO_PRIMARY_PACKAGE:

CARGO_PRIMARY_PACKAGE — This environment variable will be set if the package being built is primary. Primary packages are the ones the user selected on the command-line, either with -p flags or the defaults based on the current directory and the default workspace members. This environment variable will not be set when building dependencies. This is only set when compiling the package (not when running binaries or tests).

So the environment variable is set when compiling the package, but not set when it is used as a dependency.

Some quick tests with a bin crate which relies on a lib crate with the following const show that it seems to be working as expected:

pub const IS_A_DEP: bool = option_env!("CARGO_PRIMARY_PACKAGE").is_none();

That is, IS_A_DEP is false when only building the lib crate containing IS_A_DEP, and true when building the bin with that lib crate in its [dependencies] section.

1 Like

Hmm, is there any way to do conditional compilation based on that?

You could detect this environment variable in a build script, then use "cargo:rustc-cfg=KEY" to expose it to the program or library as #![cfg(KEY)].

We see. And is there any way to change one's own [dependencies] based on that?

(The goal is to make it a completely different crate when it's being built vs when it's being depended on. Because bins can't be cdylibs. And you can't have per-bin dependencies anyway. (And you can't stop the bin from having a dependency on the crate's own lib.))

No; platform specific dependencies and feature flags are the only options that can affect dependencies.

Ugh fine guess we'll just not support hexchat on wasm.

Can we at least change crate-type based on cfg()? Or we guess we might be able to just use crate-type=['lib', 'cdylib']?

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.