[pre-RFC] cfg(crate_root)



Conditional compilation based on whether this is a root crate or a dependency.


dbg!() and other debugging things may want to only activate when the crate is being actively developed, not used as a dependency.

Guide-level explanation

Cargo knows if this is a root crate or a dependencly and can specify a --cfg to rustc. Rustc makes it available to the code just like with cfg(feature = ...).

Unresolved questions

  • Shall it be not just a crate root, but also all crates in root workspace? When compiling an example, shall the main crate be also like a crate root?
  • Are there other use cases, not for debugging?
  • Mix with features (--cfg feature=crate_root) or something stand-alone (--cfg crate_root)?


  • Code that relies on this feature may suddenly break only when used as a dependency, compilcating debugging;


The term “crate root” usually designates the src/lib.rs or src/main.rs file, i.e. the module at the root of a crate. You’re talking about something else, i.e. whether the crate is being built as a dependency for another package or not. Therefore, I think the name crate_root is not suitable here.

I also want to emphasize the distinction between a crate and a package. A package can build several crates: a library, binaries, tests, examples, etc. Presumably, the condition should evaluate to true when building the library for use in a test, even if the library is not the “root crate” in this scenario.

You also mention Cargo workspaces. A workspace is comprised of packages, not of crates.

Considering all of this, I would suggest naming the configuration option something like root_package, main_package or target_package. Perhaps it would be interesting to have an option for the current workspace in addition to the former; the name I have in mind is workspace_member (when compiling dependencies, workspaces are not involved).