cfg attribute for conditional compilation
Marcus Chen
Jan 2026
1 tab
#[cfg(target_os = "linux")]
fn platform_specific() {
println!("Running on Linux");
}
#[cfg(target_os = "windows")]
fn platform_specific() {
println!("Running on Windows");
}
fn main() {
platform_specific();
}
1 file · rust
Explain with highlit
The #[cfg(...)] attribute enables conditional compilation based on features, target OS, or build profiles. I use #[cfg(test)] for test-only code, #[cfg(target_os = \"linux\")] for platform-specific logic, and #[cfg(feature = \"...\")] for optional features. The compiler excludes disabled code entirely, so there's no runtime cost. For inline conditions, use cfg!(...) which evaluates to a boolean. I also use #[cfg(debug_assertions)] for debug-only checks. Conditional compilation is powerful for cross-platform libraries, feature flags, and test utilities. It keeps the codebase clean and binaries small.