cargo 构建在代码中看到我的 cfg(),但在我的 Cargo.toml 中看不到,导致无法解析的导入

问题描述 投票:0回答:1

我想要一个仅在启用我的特殊 cfg 时才存在的依赖项。

简单的示例项目:
main.rs:

fn main() {
    test()
}

#[cfg(my_cfg)]
fn test() {
    use inotify::Inotify;
    println!("my_cfg is enabled")
}

#[cfg(not(my_cfg))]
fn test() {
    println!("my_cfg is not enabled")
}

build.rs:

use std::env;
fn main() {
    println!("cargo:rerun-if-env-changed=MYENV");
    if let Ok(config) = env::var("MYENV"){
        match config.as_str() {
            "my_cfg"=>println!("cargo:rustc-cfg=my_cfg"), 
            _=>{}
        }
    }
}

Cargo.toml:

[package]
name = "hello"
version = "0.1.0"
edition = "2021"

[target.'cfg(my_cfg)'.dependencies]
inotify = "0.10.2"

当我跑步时:

cargo run

我得到了我的预期输出:

"my_cfg is not enabled"

但是当我跑步时:

MYENV=my_cfg cargo run

我将收到未解决的导入“inotify”错误:

error[E0432]: unresolved import `inotify`
 --> src/main.rs:7:9
  |
7 |     use inotify::Inotify;
  |         ^^^^^^^ use of undeclared crate or module `inotify`

For more information about this error, try `rustc --explain E0432`.
error: could not compile `hello` (bin "hello") due to previous error

这意味着在我的 main.rs 中选择了正确版本的测试函数,即启用了 my_cfg。
但在我的 Cargo.toml 中,我的依赖项未被识别。

当我使用 --verbose 选项运行 Cargo build 来查看 rustc 调用时,我可以在其中看到 --cfg my_cfg 。

这是怎么回事?
如果我阅读文档,我相信我做得对:
https://doc.rust-lang.org/cargo/reference/specifying-dependency.html

rust rust-cargo
1个回答
0
投票

[target]
表中的依赖项仅适用于特定于平台的依赖项,不适用于任意
cfg
值。

如果您想知道您的平台上有哪些 cfg 目标可用,请从命令行运行

rustc --print=cfg
。如果您想知道哪些
cfg
目标可用于其他平台(例如 64 位 Windows),请运行
rustc --print=cfg --target=x86_64-pc-windows-msvc

与 Rust 源代码不同,您不能使用

[target.'cfg(feature = "fancy-feature")'.dependencies]
基于可选功能添加依赖项。请使用
[features]
部分来代替

您只能使用

cfg
列出的
rustc --print=cfg
选项。

正如文档所述,您可以使用某个功能来代替。

© www.soinside.com 2019 - 2024. All rights reserved.