如何将 rustc 标志传递给 cargo?

46

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

cargo build -- -A dead_code

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

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

2个回答

66

您可以通过多种方式通过Cargo传递标志:

  • cargo rustc,仅影响您的创建物而不影响其依赖项。
  • RUSTFLAGS 环境变量,同时影响依赖项。
  • 一些标志有正确的 Cargo 选项,例如-C lto-C panic=abort 可以在 Cargo.toml 文件中指定。
  • 使用 .cargo/config 中的 rustflags= 键添加标志。

然而,在您特定的配置 Lint 的情况下,您不需要使用编译器标志;您也可以直接在源代码中使用属性启用和禁用 Lint。实际上,这可能是更好的选择,因为它更加强大、更具针对性,而且不需要您改变构建系统设置:

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

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

另请参阅:


4
在bash中,RUSTFLAGS="-C opt-level=3 -C debuginfo=0" cargo build --release将构建一个经过优化(用于速度)的发布版本,并去除调试符号(用于减小文件大小)。 - U007D
无法运行。在可执行文件的调试信息中仍然包含硬编码的路径名,例如“a Display implementation returned an error unexpectedly C:\Users\...” - GirkovArpa
@GirkovArpa 请参考 https://dev59.com/014b5IYBdhLWcg3whSBC#54842093,了解如何完全最小化 Rust 可执行文件的大小。 - U007D

2
您可以通过修改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"]

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接