Explain the check_cfg warning in recent Rust versions—how to handle conditional…
- User
Explain the
check_cfgwarning in recent Rust versions—how to handle conditional compilation flags properly. Assistant
Explain the check_cfg warning in recent Rust versions—how to handle conditional compilation flags properly.
1. Understand the User's Request:
* Topic: check_cfg warning in Rust.
* Context: "Recent Rust versions" (specifically, this feature has been rolling out and becoming more prominent, notably around Rust 1.80 or via Cargo.toml configuration in earlier versions).
* Goal: Explain what it is and how to handle conditional compilation flags (cfg) properly to resolve these warnings.
Deconstruct check_cfg:
cfg conditional compilation checks are expected/well-formed.#[cfg(feature = "super_feture")] instead of super_feature, Rust previously ignored it silently if the condition was false. Now, it warns if it doesn't recognize the condition.#[cfg(...)], #[cfg_attr(...)], or cfg!(...) with names (features, os, families, etc.) that Cargo/rustc hasn't been told are valid possibilities.Identify the "Pain Points" (Why users see this now):
Cargo.toml.Determine Solutions/Handling Strategies:
Scenario A: Typos. (The happy path).
Scenario B: Valid features/flags that Rust thinks are unknown.
Cargo.toml [lints.rust]. (The "Ignore specific ones" approach).Cargo.toml [package.metadata/check_cfg] or similar? No, that's old. The modern way is usually just defining the features properly in [features] or using [lints].rustflags config. Specifically -Zcheck-cfg.[features]. The issue usually arises with well-known names (like unix) or names passed via the command line that aren't in the manifest.Wait, let's refine how check_cfg works with Cargo.
--check-cfg to rustc.cfg() specs for features in [features].cfg() specs for built-in targets (windows, unix).#[cfg(feature = "dep_feature")], this is usually fine if the dependency enables it.#[cfg(foobar)] but foobar isn't a built-in config or a feature, it warns.Structure the Explanation:
Introduction: Define unexpected_cfgs (the lint name associated with check_cfg). Explain the goal (catching typos).
The "Why": The typo scenario.
The Warning: Show an example of what it looks like (warning: unexpected cfg condition value).
How to Handle It (The 3 Tiers):
[lints.rust.unexpected_cfgs] (if applicable, though usually, the lint is controlled by compiler flags or [package.metadata]? Self-correction: Actually, Cargo handles the specification of expected values via [features] for features. But what about arbitrary names?rustflags = ["--cfg", "my_flag"] in .cargo/config.toml OR ensuring the feature is in Cargo.toml.[features].
If it's a custom config (like docsrs for docs), you need to tell Cargo to expect it.Cargo.toml (The "expected" list):
[lints]? No, unexpected_cfgs can't be easily configured via [lints] to add allowed values, the allowed values are passed to the compiler.[package.metadata.docs.rs] or standard [features].Cargo.toml or pass specific flags.Refined Strategy for "How to handle":
[features]. If it's a feature of a dependency, you usually can't check it directly unless you enable it. (Wait, checking #[cfg(feature = "serde")] when serde is a dependency is valid if serde is optional).Detailed "How-To" Steps:
Step 1: The Warning.
warning: unexpected cfg condition value: 'super_feture' -> Typo.warning: unexpected cfg condition name: 'my_custom_flag' -> Not registered.Step 2: Registering Features.
my_custom_flag = [] to [features] in Cargo.toml.Step 3: Handling Non-feature Configs (e.g., for docs.rs).
#[cfg(doc)] is fine. #[cfg(docsrs)] is a convention but not built-in.rustflags in .cargo/config.toml.Step 4: Disabling the Lint (Last resort).
[lints.rust] unexpected_cfgs = "allow" (or "warn").Reviewing the "Recent Rust Versions" aspect:
check_cfg by default for Cargo projects? No, it was earlier that it started warning, but it became strict/intrusive recently.--check-cfg automatically.Drafting the Content (Mental Draft):
feature = "btreemap" instead of feature = "btree-map".Cargo.toml.
[features]. Even if it has no dependencies.docsrs).
.cargo/config.toml to set rustflags.Refining the .cargo/config.toml solution:
If I just pass --cfg docsrs in rustflags, check_cfg might still complain if I don't also say "expect this config".
Actually, passing --cfg docsrs implicitly tells check_cfg that docsrs is a valid configuration option? Yes, usually --cfg foo adds foo to the configuration and the list of expected config options? No, explicit --check-cfg is needed.
Correction: Cargo handles the --check-cfg generation. If you use a custom cfg, you have to manually allow it or ensure Cargo knows about it.
Let's verify the specific syntax for allowing custom values.
The warning says: note: expected values for 'feature' are: ...
If the user wants to allow my_cfg, they can add my_cfg to [features] as a "virtual" feature.
Alternatively, they can suppress the lint in lib.rs (#![allow(unexpected_cfgs)]).
The most robust way for recent versions:
Since Rust 1.80, Cargo automatically checks all features in [features].
If you are checking a feature that isn't there (e.g., a feature of a dependency that you didn't mark as default?), that's a logic error usually, but sometimes done.
Crucial point: The warning usually tells you exactly what to do.
Let's structure the advice around the unexpected_cfgs lint.
[features] in Cargo.toml. This is the most common fix.
#[cfg(feature = "serde")]. You must have serde = ["dep:serde"] in [features].#[cfg(my_build_flag)].#![allow(unexpected_cfgs)] or tell Cargo via [lints]? No, [lints] is for setting severity.Cargo.toml keys (unlike features).my_build_flag = [].docsrs is the classic culprit.
Here is an explanation of why this warning exists and how to handle it properly.
check_cfg warning?The warning usually looks like this:
warning: unexpected `cfg` condition value: `my_feature`
--> src/main.rs:4:7
|
4 | #[cfg(feature = "my_feature")]
| ^^^^^^^^^^^^^^^^^^^^^^^
|
= note: expected values for `feature` are: `std`, `full`
= help: consider adding `my_feature` to the list of expected values
The Goal:
This warning exists to catch typos. Previously, if you wrote #[cfg(feature = "ssuper")] (misspelled "super"), Rust would silently ignore the code block because the condition was false. If you intended to compile specific code, it would be skipped without warning, leading to hard-to-debug issues.
How it works: The compiler now maintains a list of "expected" configuration options.
unix, windows, target_arch).Cargo.toml [features] table.If you use a cfg value that isn't in that list, the compiler warns you.
There are three ways to resolve this warning, depending on what you are trying to do.
Cargo.toml (Most Common)If you are using #[cfg(feature = "foo")], the cleanest solution is to explicitly declare foo in your Cargo.toml, even if it currently has no dependencies.
In Cargo.toml:
[features]
default = []
foo = [] # <--- Add the feature here
By adding it here, Cargo tells the Rust compiler: "This is a valid feature name." The warning will disappear, and you can toggle it via command line (cargo build --features foo).
Sometimes you want to use a cfg flag that isn't a Cargo feature (e.g., logic controlled by a build script or a custom environment variable).
If you are intentionally using a flag that isn't in Cargo.toml, you should tell Cargo to expect it. You can do this in Cargo.toml under [lints].
In Cargo.toml:
# Tell Cargo that "my_custom_flag" is a valid cfg name
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(my_custom_flag)'] }
Note: In older versions or specific setups, you might need to pass this via rustflags in .cargo/config.toml, but the [lints] table is the modern way.
If you are doing complex conditional compilation (e.g., dependencies setting flags dynamically) and you cannot easily predict the flags, you can suppress the warning.
In your code (usually lib.rs or main.rs):
#![allow(unexpected_cfgs)]
// Your code below...
#[cfg(weird_undefined_flag)]
fn my_func() {}
Or globally in Cargo.toml:
[lints.rust]
unexpected_cfgs = "allow"
feature_name = [] to the [features] section of Cargo.toml.[lints.rust.unexpected_cfgs] in Cargo.toml so the compiler expects it.target_os = "linux"). These are built-in. If it warns here, it's usually a typo (e.g., linuz).docsrs). This is the most common source of complaints. The solution is usually to tell Cargo/Rustc that this is expected.
.cargo/config.toml: rustflags = ["--cfg", "docsrs"].Cargo.toml, under [lints.rust], setting unexpected_cfgs level? No, that disables the check entirely.[package] key or [lints] interaction?--check-cfg arguments.foo but it's not in [features] (maybe passed via command line), you should add foo to [features].docsrs to [features].Self-Correction on Lints in Cargo.toml:
You can configure the lint level in Cargo.toml:
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(my_custom_flag)'] } # This syntax isn't real yet?
No, currently, to allow arbitrary configs, you often have to define them as features in Cargo.toml or suppress the lint.
Wait, there is a specific update in 1.80 regarding this.
If a user writes #[cfg(has_foo)], they should define has_foo in [features].
Let's stick to the practical solutions.
Structure for Final Output:
unexpected_cfgs).Cargo.toml).cfg in code or allow).Refining Scenario C:
If you have a script that sets RUSTFLAGS="--cfg my_custom_flag", Rust 1.80+ will warn that it doesn't expect that flag.
To fix this, you need to tell Rust to expect it.
Currently, the best way is to define a feature in Cargo.toml: my_custom_flag = [].
Wait, feature != generic cfg.
If I write #[cfg(feature = "foo")], foo must be in features.
If I write #[cfg(foo)], foo is a generic cfg.
If I have a generic cfg, Cargo doesn't know about it.
There isn't a standard [package.metadata.check-cfg] key in stable Cargo yet to list expected generic cfgs (unlike features).
Therefore, the solution for generic cfg keys is often:
feature.#![allow(unexpected_cfgs)].--check-cfg via rustflags manually (advanced/verbose).Let's keep it simple. The user likely encountered this because of a feature or a typo. I will focus on Cargo.toml features as the primary fix, and #![allow(...)] for edge cases.
Addendum: Rust 1.80.0 Release Notes.
"Cargo will now automatically check cfg names and values."
It lists unexpected_cfgs as the lint.
It recommends adding features to Cargo.toml or suppressing the lint.
Plan:
unexpected_cfgs lint.Cargo.toml. (Most common)..cargo/config.toml).Self-Correction on target_ cfgs:
If someone writes #[cfg(target_os = "redhat")], it will warn because redhat isn't a known value for target_os. This is correct behavior. The fix is to remove it or use a custom cfg.
Code Examples:
Show Cargo.toml and main.rs interaction.
Tone: Helpful, technical, focused on "how to fix".
Summary of "How to handle":
[features].docsrs), add it to [features] as a dummy.Let's generate the response based on this logic.
In recent Rust versions (specifically starting with Rust 1.80, which made unexpected_cfgs a warning by default), you may see new warnings related to cfg (conditional compilation). This is part of an effort to make configuration checks safer and to prevent typos.