rust - 在 `cfg` 宏下使用条件编译模块

标签 rust conditional-compilation

我想知道如何使用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`

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

最佳答案

#[cfg]属性将有条件地编译代码,cfg! is 给出等效的 bool 值(例如 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

关于rust - 在 `cfg` 宏下使用条件编译模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62350046/

相关文章:

c - #ifdef MACRO 是否等同于注释

rust - 如何向 tokio-io 添加特殊的 NotReady 逻辑?

rust - 当我在结构中使用可变引用而不是不可变引用时,为什么会出现生命周期错误?

gcc - 在编译时确定 LLVM 与 GCC

build-process - CoffeeScript/UglifyJS 中的条件编译

c - 如何通过 CompilerType #ifdef ?海湾合作委员会或 VC++

csv - 使用 Serde 将结构实例写入文件时如何向结构实例添加额外的数据点?

rust - 我如何使用另一个模块的私有(private)特征?

rust - 在 Rust 中,将带有可选参数的平面 JSON 反序列化为嵌套结构和枚举

c - 如何让 GCC (Xtensa 5.1) 识别定义