【问题标题】:Conditional Compilation Shorthand条件编译简写
【发布时间】:2020-08-21 18:36:48
【问题描述】:

在我的.toml 文件中,我定义了一个默认关闭的功能:

[features]
foo = []

如果启用此功能,我想打印“FOO”:

fn main() {
    #[cfg(feature = "foo")]
    println!("FOO");
}

然后我可以像这样编译(并运行)代码:cargo run --features foo

但是,我更喜欢使用在docs 中看到的速记。像这样的:

fn main() {
    #[cfg(foo)]
    println!("FOO");
}

但是,当使用与之前相同的cargo run 命令时,打印语句无法编译。我错过了什么?

【问题讨论】:

  • 好吧,这不是查询属性的语法。你可以实现一个 proc 宏,这样你就可以写 #[foo] 而不是 #[cfg(feature = "foo")] 如果你真的想要,但在我看来,简单地使用其他人使用的语法会使代码更容易理解。
  • @SvenMarnach 在上面给出的链接中,文档中给出示例时的含义:#[cfg(not(foo))]。在这种情况下,foo 是什么?
  • @HiDefender // This function is only included when foo is not defined。打开功能“foo”就是将 value foo 添加到 feature,定义 feature

标签: rust compilation conditional-compilation


【解决方案1】:

根据docs.

#[cfg(foo)] 是配置选项名称。并且可以这样设置:rustc --cfg foo main.rs。货物设置方法见this question

#[cfg(feature = "foo")] 是配置选项键值对。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-03
    • 2012-04-01
    • 2012-12-22
    • 2015-06-09
    • 2010-11-15
    • 2023-03-05
    • 2013-07-22
    • 1970-01-01
    相关资源
    最近更新 更多