I want to know how I can compile this code under linux

I am writing a program that calls different APIs according to different platforms, but the problem is that if I develop on linux, winapi will not pass the compilation, and if I develop on windows, the related content of linux will not compile, what should I do?

Cross compile? I'm sorry your question seems very vague to me and I don't understand what your problem is.

You can use conditional compilation to only compile the platform specific parts of your code when building for the associated platform

2 Likes

Thanks, this can helped me, I'm not very familiar with rust

Thank you for your reply it has been resolved

After using conditional compilation, a new problem appeared, how can I solve it, the code is as follows:


error: failed to resolve: use of undeclared crate or module linux
label: use of undeclared crate or module linux

You're mixing conditional compilation with runtime checks for cfgs which don't affect compilation. You shouldn't need an OS enum.

The more verbose way to do this is by applying cfg attributes to blocks

pub fn get_system_metrics() -> (i32, i32) {
    #[cfg(windows)]
    {
        win::get_system_metrics()
    }

    #[cfg(target_os = "linux")]
    {
        linux::get_system_metrics()
    }
}

The way the standard library tends to do it is by aliasing modules, though this requires the signatures of all the items you use to be compatible

#[cfg(windows)]
use win as implementation;

#[cfg(target_os = "linux")]
use linux as implementation;

pub fn get_system_metrics() -> (i32, i32) {
    // This line is the same for all platforms, but implementation refers to a platform specific module
    implementation::get_system_metrics()
}

The cfg-if crate can also make the first version more readable.

6 Likes

Thanks, the habit of writing code in other languages is killing me

Side note, please post code and errors as text, not as images.

3 Likes

ok next time pay attention

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.