43

I am trying to disable dead code warnings. I tried the following

cargo build -- -A dead_code

➜ rla git:(master) ✗ cargo build -- -A dead_code error: Invalid arguments.

So I am wondering how would I pass rustc arguments to cargo?

Maik Klein
  • 15,548
  • 27
  • 101
  • 197

2 Answers2

61

You can pass flags through Cargo by several different means:

  • cargo rustc, which only affects your crate and not its dependencies.
  • The RUSTFLAGS environment variable, which affects dependencies as well.
  • Some flags have a proper Cargo option, e.g., -C lto and -C panic=abort can be specified in the Cargo.toml file.
  • Add flags in .cargo/config using one of the rustflags= keys.

However, in your specific case of configuring lints, you don't need to use compiler flags; you can also enable and disable lints directly in the source code using attributes. This may in fact be a better option as it's more robust, more targeted, and doesn't require you to alter your build system setup:

#![deny(some_lint)] // deny lint in this module and its children

#[allow(another_lint)] // allow lint in this function
fn foo() {
    ...
}

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 3
    E.g. In bash, `RUSTFLAGS="-C opt-level=3 -C debuginfo=0" cargo build --release` will build an optimized (for speed) release build stripped of debug symbols (for size). – U007D Dec 11 '19 at 05:53
  • Does not work. Still contains hardcoded pathnames in debug information in the executable; e.g. `a Display implementation returned an error unexpectedly C:\\Users\\...` – GirkovArpa Feb 16 '21 at 07:37
  • @GirkovArpa see https://stackoverflow.com/a/54842093/1541330 for how to fully minimize the size of a Rust executable. – U007D Oct 17 '21 at 14:16
2

You can disable dead code warnings by modifying config.toml file. if file doesn't exists create one as below locations.

Windows: %USERPROFILE%\.cargo\config.toml
Unix: $HOME/.cargo/config.toml

Then add below line

[target.'cfg(target_family = "windows")']
rustflags = ["-Adead_code"]

If you dont want to see any unused variable warnings add below line

[target.'cfg(target_family = "windows")']
rustflags = ["-Aunused"]

Don't forget to disable these before Production :)

Kargat TTT
  • 21
  • 1