6

Is it possible to mark certain includes to only get included on relevant OS's?

For example, can you do something like:

#[cfg(unix)] {
    use std::os::unix::io::IntoRawFd;
}
#[cfg(windows)] {
   // https://doc.rust-lang.org/std/os/unix/io/trait.AsRawFd.html  suggests this is equivalent?
   use std::os::windows::io::AsRawHandle;
}

Trying to compile the above code gives me syntax errors (i.e. error: expected item after attributes).

I'm trying to patch a Rust project I found on GitHub to compile on Windows (while still making it retain the ability to be compiled on its existing targets - i.e. Unixes & WASM). Currently I'm running into a problem where some of the files import platform-specific parts from std::os (e.g. use std::os::unix::io::IntoRawFd;), which ends up breaking the build on Windows.

Note: I'm using Rust Stable (1.31.1) and not nightly.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
Joshua Leung
  • 169
  • 2
  • 10
  • 1
    Yes it is possible, just leave out `{` and `}`. So your example is just a typographical error. Also see https://doc.rust-lang.org/reference/conditional-compilation.html – hellow Feb 04 '19 at 12:27

1 Answers1

8

The syntax you are looking for is:

#[cfg(target_os = "unix")]
use std::os::unix::io::IntoRawFd;

#[cfg(target_os = "windows")]
use std::os::windows::io::AsRawHandle;
Stargateur
  • 24,473
  • 8
  • 65
  • 91
Chen Levy
  • 15,438
  • 17
  • 74
  • 92