【问题标题】:Using conditionally compiled module under `cfg` macro在“cfg”宏下使用条件编译模块
【发布时间】:2020-06-12 18:07:27
【问题描述】:

我想知道如何在cfg! 宏下使用条件编译模块。我正在尝试这个:

pub fn f() { ... }

#[cfg(feature = "x")]
pub mod xmodule {
   pub fn f() { ... }
}

pub fn test() {
  if cfg!(feature = "x") {
    xmodule::f();
  } else {
    f();
  }; 
}

当我使用cargo check --features x 编译它时它工作正常,但如果我不启用该功能它会失败并出现以下错误:

use of undeclared type or module `xmodule`

是我做错了什么还是编译不够聪明,无法理解如果未设置该功能则不应使用该模块?

【问题讨论】:

    标签: rust conditional-compilation


    【解决方案1】:

    #[cfg] 属性将有条件地编译代码,cfg! 给出等效的布尔值(例如,true 如果启用了某个功能,false 否则)。所以你的代码基本上编译成:

    pub fn test() {
      if false { // assuming "x" feature is not set
        xmodule::f();
      } else {
        f();
      }; 
    }
    

    因此,即使只运行了一个分支,两个分支仍必须包含有效代码。

    要获得实际的条件编译,您可以这样做:

    pub fn test() {
      #[cfg(feature = "x")]
      fn inner() {
        xmodule::f()
      }
    
      #[cfg(not(feature = "x"))]
      fn inner() {
        f()
      }
    
      inner();
    }
    

    Playground example

    或者您可以使用第三方宏,例如cfg-if

    use cfg_if::cfg_if;
    
    pub fn test() {
      cfg_if! {
        if #[cfg(feature = "x")] {
          xmodule::f();
        } else {
          f();
        }
      }
    }
    

    Playground example

    【讨论】:

      猜你喜欢
      • 2015-02-22
      • 2015-02-11
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多