如何将 rustc 标志传递给货物?

How to pass rustc flags to cargo?

我正在尝试禁用死代码警告。我尝试了以下

cargo build -- -A dead_code

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

所以我想知道如何将 rustc 参数传递给 cargo?

您可以通过几种不同的方式通过 Cargo 传递标志:

  • cargo rustc,这只会影响你的板条箱而不影响它的依赖项。
  • RUSTFLAGS 环境变量,它也会影响依赖项。
  • 一些标志有适当的 Cargo 选项,例如,-C lto-C panic=abort 可以在 Cargo.toml 文件中指定。
  • 使用 rustflags= 键之一在 .cargo/config 中添加标志。

但是,在配置 lints 的特定情况下,您不需要使用编译器标志;您还可以使用属性直接在源代码中启用和禁用 lints。这实际上可能是一个更好的选择,因为它更健壮、更有针对性,并且不需要您更改构建系统设置:

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

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

另请参阅:

  • How to disable unused code warnings in Rust?

您可以通过修改 config.toml 文件来禁用死代码警告。 如果文件不存在,请在以下位置创建一个。

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

然后在下面添加行

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

如果您不想看到任何未使用的变量警告,请在下面添加行

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

不要忘记在生产前禁用它们:)