Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a crate only for a given platform?

I would like to use the nix crate in a project.

However, this project also has an acceptable alternative implementation for OSX and Windows, where I would like to use a different crate.

What is the current way of expressing that I only want nix in Linux platforms?

like image 339
Juan Leni Avatar asked Aug 13 '18 11:08

Juan Leni


1 Answers

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:

[target.'cfg(target_os = "linux")'.dependencies]
nix = "0.5"

This will make Cargo only include the dependency when that configuration is active. However, this means you'll get a compile error on your extern crate when you try to build on other platforms! To remedy this, annotate it with a cfg attribute, like so:

#[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.

like image 122
Joe Clay Avatar answered Oct 04 '22 03:10

Joe Clay