I have a tiny Rust project, and I have a linux_specific_functions.rs file which should only be compiled in the Linux platform.
In other platforms, e.g. Windows, and macOS, it should be excluded. So the Linux-specific functions can only be found and used in Linux.
How can I do that? the cfg macro/attribute seems only available at the function level.
More specifically, the Linux platform have a 3rd party dependency which I declared in Cargo.toml:
And one more question, how can I call different code path for different target_os?
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = ...;
// This won't work
if cfg!(linux) {
linux_main(args).await
} else {
other_main(args).await
}
}
error[E0425]: cannot find function `other_main` in this scope
--> server/src/main.rs:210:9
|
210 | other_main(args).await
| ^^^^^^^^^^ not found in this scope
error: operating system used in target family position
--> src/main.rs:2:5
|
2 | #[cfg(linux)]
| ^^^^^^-----^^
| |
| help: try: `target_os = "linux"`
|
= help: did you mean `unix`?
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#mismatched_target_os
= note: `#[deny(clippy::mismatched_target_os)]` on by default
FYI, one convention for platform conditional modules is something like:
#[cfg(cond1)]
mod first_imp;
#[cfg(cond1)]
use first_imp as imp;
#[cfg(cond2)]
mod second_imp;
#[cfg(cond2)]
use second_imp as imp;
// each module should share a good amount of the same interface
// so that in your code you can just do
imp::foobar()
Personally I think a plain if/else with cfg!(target_os = "linux") as the condition would read better in this case. Are the Ok(...?) necessary when you write it like this?