Knowing if a script is running in rustdoc

I have a custom build script in a sys crate that optionally builds a static library or links to an existing library, depending on a --features flag. I don't provide a default because I am following @kornel 's advice from Using C libraries in Rust: make a sys crate i.e. "Don't put any of them as Cargo's default feature, because it's too hard to unset defaults in Cargo."

So, that means by script fails if neither the static nor the dynamic feature is set. The problem is that build doesn't set any features, even if you cargo publish --features .... So the docs build fails and no docs get published on

So, how do I detect that it's building documentation in the script so I can disable the C build steps?

Thank you.

You could add a feature flag called for example docsrs that disables the C build and then put the following in Cargo.toml:

features = ["docsrs"]

This will enable the docsrs feature when builds it.


Answering the question, the configuration doc is set under rustdoc, so the environment variable CARGO_CFG_DOC should be set under

What you said stands to reason, but sadly it doesn't appear to work. For debugging purposes, I outputted all environment vars from the build script and none of them appear to indicate that it's running from RustDoc.

I believe RustDoc builds the crate in two passes, and the first pass is an ordinary debug build without the cfg set. Perhaps to expand macros. (just my guess) Then the pass with #[cfg(doc)] set appears to come next.

Thanks for the reply anyway.

Seems to be known Cargo doc does not pass `--cfg doc` for build scripts · Issue #8944 · rust-lang/cargo · GitHub

But the linked issue there implies that you only don't get --cfg doc when it's being built as a dependency? But then it talks about cargo rustdoc vs cargo doc behavior and I've now gotten very confused.

1 Like

I was hoping to find a solution that would work for all doc builds, but it appears those cargo & rustdoc features are still upcoming. e.g. (Pre-RFC: doc-dependencies - cargo - Rust Internals), (Default cargo features should include doc-default features · Issue #1943 · rust-lang/rfcs · GitHub), etc.

In any case, [] works great to solve the problem for

Thank you!

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.