[英]How to use a crate only for a given platform?
I would like to use the nix
crate in a project. 我想在一个项目中使用
nix
crate。
However, this project also has an acceptable alternative implementation for OSX and Windows, where I would like to use a different crate. 但是,这个项目还有一个可接受的OSX和Windows替代实现,我想使用不同的箱子。
What is the current way of expressing that I only want nix
in Linux platforms? 目前的表达方式是什么,我只想在Linux平台上使用
nix
?
There's two steps you need to make a dependency completely target-specific. 您需要两个步骤才能使依赖项完全针对特定目标。
First, you need to specify this in your Cargo.toml
, like so: 首先,您需要在
Cargo.toml
指定它,如下所示:
[target.'cfg(target_os = "linux")'.dependencies]
nix = "0.5"
This will make Cargo only include the dependency when that configuration is active. 这将使Cargo仅在该配置处于活动状态时包含依赖项。 However, this means you'll get a compile error on your
extern crate
when you try to build on other platforms! 但是,这意味着当您尝试在其他平台上构建时,您的
extern crate
会出现编译错误! To remedy this, annotate it with a cfg
attribute, like so: 要解决此问题,请使用
cfg
属性对其进行注释,如下所示:
#[cfg(target_os = "linux")]
extern crate nix;
Of course, you then have to ensure that you only use the nix
crate in code that's also annotated with the same cfg
attribute. 当然,您必须确保只在代码中使用
nix
crate,该代码也使用相同的cfg
属性进行注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.