FAQ - Help and questions

How do I find out at run time which operating system and CPU my Rust program is on?

#cfg#platform#std#cross-platformpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

std::env::consts has OS, ARCH and FAMILY strings, which describe the system the program was compiled for. They are fixed at build time, so a program built for Windows always reports windows, even under emulation. For OS version numbers you need a system call or a crate.

Checked with rustc 1.93.0, Windows 11 on a 64-bit x86 CPU; compiled and run. The values for macOS are from std's documentation (macos, aarch64 or x86_64) and were not run.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Use the constants in std::env::consts:

src/main.rsrust
use std::env::consts::{ARCH, FAMILY, OS};

fn main() {
    println!("OS = {OS}, ARCH = {ARCH}, FAMILY = {FAMILY}");
    println!("compiled for Windows: {}", cfg!(windows));
    println!("pointer width: {}", cfg!(target_pointer_width = "64"));
}
text
OS = windows, ARCH = x86_64, FAMILY = windows
compiled for Windows: true
pointer width: true

What the values are, according to std's documentation: OS is a string such as "windows", "macos" or "linux"; ARCH is such as "x86_64" or "aarch64" (an Apple silicon Mac build reports aarch64); FAMILY is "unix" or "windows".

Important: these are compile-time facts. They say what the executable was built for, not what it runs on:

  • A program built for x86_64 and run on an Apple silicon Mac through Apple's translation layer still reports x86_64. The same applies to emulated x86 programs on Windows on Arm.
  • They tell you nothing about the version (Windows 10 or 11, macOS 14 or 15). Ask the system for that: use a crate designed for it, or the platform's API, and treat the result as informational.
  • A feature test beats a version test. If you need a function that exists from some system version on, try to load it or check for the capability, rather than comparing version numbers.

Use consts::OS for log lines, bug-report text ("running on ...") and choosing a download file name. Use #[cfg] when different code must be compiled in (see the cfg threads).

Common mistakes#

  • Using OS to decide path separators. Use Path and PathBuf.
  • Using string comparison on OS where an enum would be better: match OS { "windows" => ..., "macos" => ..., _ => ... } needs a fallback arm for other values.

How do I build for both Intel and Apple silicon Macs?#

That is a packaging question: build once per CPU target and combine; see the macOS packaging threads.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet