Answer#
A crate for the Windows API is useless on a Mac, and a crate for Apple's frameworks cannot build on Windows. Cargo lets you attach dependencies to a target condition, using the same cfg expressions as the code:
[package]
name = "demo"
version = "0.1.0"
edition = "2021"
# Only compiled and linked on Windows:
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging"] }
# The same syntax for macOS (an example; not built here):
# [target.'cfg(target_os = "macos")'.dependencies]
# some-macos-crate = "1"#[cfg(windows)]
fn beep_name() -> &'static str {
// Referencing the constant proves the crate is really linked on this platform.
let _ = windows_sys::Win32::UI::WindowsAndMessaging::MB_OK;
"windows-sys is available"
}
#[cfg(not(windows))]
fn beep_name() -> &'static str {
"no windows-sys on this system"
}
fn main() {
println!("{}", beep_name());
}windows-sys is availableThe dependency is declared for Windows only, so on another system Cargo does not compile it; the code that uses it must be guarded by the matching #[cfg], or the other system's build fails with "unresolved crate".
Other forms that work the same way: [target.'cfg(unix)'.dependencies], [target.'cfg(not(windows))'.dependencies], and a full target triple such as [target.x86_64-pc-windows-msvc.dependencies]. The same applies to [target.….build-dependencies] and [target.….dev-dependencies].
Cargo's Cargo.lock still records every dependency for every system, so the lock file is the same on every machine and builds stay reproducible.
Common mistakes#
- Putting the dependency in
[dependencies]and guarding only the code. Cargo still downloads and builds it on every system, and it may fail to build. - Enabling every feature of a big API crate. Turn on only the API areas you call (
Win32_UI_WindowsAndMessagingabove); build time falls. - Writing
cfg(macos). There is no such cfg; usecfg(target_os = "macos").
Related questions#
Can I check the macOS build on a Windows PC?#
For pure-Rust code you can ask the compiler to type-check for another target if the standard library for that target is installed (with rustup, rustup target add aarch64-apple-darwin, then cargo check --target aarch64-apple-darwin). That was not tried here, because this machine's toolchain was installed without rustup. Crates that need Apple's SDK (linking, C code) will not build without it, so keep a macOS CI job.
Sources#
- The Cargo Book, platform-specific dependencies: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#platform-specific-dependencies (read 2026-12-05)
- windows-sys: https://docs.rs/windows-sys/ (read 2026-12-05)