How to mark use statements for conditional compilation? [duplicate]
Asked Answered
B

1

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.

Boyles answered 4/2, 2019 at 12:20 Comment(1)
Yes it is possible, just leave out { and }. So your example is just a typographical error. Also see doc.rust-lang.org/reference/conditional-compilation.htmlSuicidal
R
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;
Roanne answered 4/2, 2019 at 13:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.