Feature in rust config

I'd like change rustflags depends on feature

so I wrote below to .cargo/config.toml

[target.'cfg(feature="my_opt")']
rustflags = "--cfg my_opt"

and I added my_opt feature to Cargo.toml

and the main code is

fn main() {
  if cfg!(my_opt) {
     println!("my_opt");
  } else {
     println!("no my_opt");
  }
}

I tested with cargo run and cargo run -F my_opt

Two of execute results are same.
Why config.toml was not working?

it is not supported. the document says:

cfg values come from those built-in to the compiler (run rustc --print=cfg to view), values set by build scripts, and extra --cfg flags passed to rustc (such as those defined in RUSTFLAGS). Do not try to match on debug_assertions or Cargo features like feature="foo"

you should use build scripts for such use cases. specifically, your script should set cargo:rustc-flags=XXXX and/or cargo:rustc-cfg=KEY[=VALUE]. see

https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script

1 Like