【问题标题】:How do I use conditional compilation with `cfg` and Cargo?如何将条件编译与 `cfg` 和 Cargo 一起使用?
【发布时间】:2015-02-22 07:42:54
【问题描述】:

我想使用 cfg 和 Cargo 有条件地编译我的源代码, 谷歌搜索了一段时间后, 看来解决方案是使用cargo --features。

http://doc.crates.io/manifest.html

我尝试添加一些

#[cfg(feature = "foo")]

在源代码中和

cargo build --features foo

,但它说

Package `xxx v0.0.1 (file:///C:/yyy/xxx)` does not have these features: `foo`

如何让 cargo 识别特征?我必须在Cargo.toml 中添加一些内容吗?

这是我正在使用的rustc 和cargo 的版本:

C:\>rustc --version
rustc 0.13.0-nightly (42deaa5e4 2014-12-16 17:51:23 +0000)

C:\>cargo --version
cargo 0.0.1-pre-nightly (5af754d 2014-12-18 01:50:48 +0000)

【问题讨论】:

    标签: rust rust-cargo


    【解决方案1】:

    您必须在Cargo.toml 中介绍现有功能。

    我能够通过执行以下操作有条件地编译:

    • 在Cargo.toml中,创建features部分并引入某个功能名称:

      [features]
      
      customfeature = [] # feature has no explicit dependencies
      

      如果您希望您的功能具有特定的依赖关系,请检查the examples in the documentation。

    • 在您的代码中,使用#[cfg(feature="customfeature")]

    • 运行cargo build --features customfeature

    由于您的步骤 2 和 3 似乎没问题,您的 Cargo.toml 可能有问题。

    【讨论】:

    • 是否可以测试“if”中的功能?谢谢。
    • @BulatM。是的,您可以使用if cfg!(feature = "customfeature") { ... }
    【解决方案2】:

    如其他答案所述,您可以为此使用features。我想补充一点,这些功能不仅允许您有条件地编译部分代码,而且还可以有条件地包含可能是该代码一部分的依赖项。考虑以下 sn-ps:

    您可以使用其他答案中已经描述的功能标志来激活条件代码:

    cargo build --features customfeature
    

    仅当您的customfeature 启用时,您才需要将条件代码标记为存在:

    #[cfg(feature = "customfeature")]
    fn my_func() {
        my_optional_dependency::do_something(); 
    }
    
    // This includes dependencies only when customfeature is enabled
    #[cfg(feature = "customfeature")] 
    extern crate my_optional_dependency;
    ....
    
    #[cfg(feature = "customfeature")]
    use my_optional_dependency::*;
    ....
    

    您的Cargo.toml 需要包含以下部分:

    [dependencies.my_optional_dependency]
    version = "1.2.3"
    optional = true
    
    [features]
    customfeature = ["my_optional_dependency"]
    

    这允许您仅在启用某个功能时激活代码的某些部分及其依赖项。

    【讨论】:

    • 谢谢亚历克斯!阅读您的回答后,我想我终于完全理解了 Rust 的功能。
    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2013-02-01
    • 2016-08-10
    • 2019-12-11
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    相关资源
    最近更新 更多