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

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

[我想知道如何在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个回答
0
投票

虽然#[cfg]属性将有条件地编译代码,但cfg!只是布尔值本身。因此,您的代码基本上可以编译为:

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

cfg-if

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

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