我想cfg
用Cargo 有条件地编译我的源代码,在谷歌搜索一段时间后,似乎解决方案是使用cargo --features
.
http://doc.crates.io/manifest.html
我尝试添加一些
#[cfg(feature = "foo")]
Run Code Online (Sandbox Code Playgroud)
在源代码和
cargo build --features foo
Run Code Online (Sandbox Code Playgroud)
,但它说
Package `xxx v0.0.1 (file:///C:/yyy/xxx)` does not have these features: `foo`
Run Code Online (Sandbox Code Playgroud)
我怎样才能让货物识别出这些特征?我必须添加一些东西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)
Run Code Online (Sandbox Code Playgroud)
blu*_*e10 19
你必须介绍你的现有功能Cargo.toml
.
通过执行以下操作,我能够有条件地编译:
在Cargo.toml
,创建一个features
部分并介绍某个功能名称:
[features]
customfeature = [] # feature has no explicit dependencies
Run Code Online (Sandbox Code Playgroud)
如果您希望您的功能具有特定的依赖项,请查看文档中的示例.
在您的代码中,使用 #[cfg(feature="customfeature")]
跑 cargo build --features customfeature
由于您的步骤2和3似乎没问题,因此您的问题可能一定存在问题Cargo.toml
.
小智 12
或者,您可以在项目主文件夹中创建一个子目录.cargo
,在其中添加一个config.toml
文件,然后将此部分插入到 .cargo/config.toml
:
[build]
rustflags = "--cfg my_cfg_flag"
Run Code Online (Sandbox Code Playgroud)
这将使货物调用带有标志--cfg my_cfg_flag的rustc
有关详细信息,请参阅此处: https ://doc.rust-lang.org/cargo/reference/config.html
正如其他答案中所述,您可以使用features
它。我想补充一点,这些功能不仅允许您有条件地编译部分代码,还允许有条件地包含可能是该代码一部分的依赖项。考虑以下片段:
您可以使用其他 anws 中已经描述的功能标志激活条件代码:
cargo build --features customfeature
Run Code Online (Sandbox Code Playgroud)
只有在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::*;
....
Run Code Online (Sandbox Code Playgroud)
您Cargo.toml
需要具有以下部分:
[dependencies.my_optional_dependency]
version = "1.2.3"
optional = true
[features]
customfeature = ["my_optional_dependency"]
Run Code Online (Sandbox Code Playgroud)
这允许您仅在启用某个功能时激活代码的某些部分及其依赖项。
归档时间: |
|
查看次数: |
9732 次 |
最近记录: |