Fundamentals 11 min read

Master Rust Conditional Compilation: From #[cfg] to cfg! with Real-World Examples

This guide thoroughly explains Rust's conditional compilation, covering the #[cfg] attribute, the cfg! macro, custom feature flags, dependency selection, testing, and practical GUI demos, providing code snippets and best practices for writing portable, maintainable cross‑platform Rust applications.

Big Data Technology Tribe
Big Data Technology Tribe
Big Data Technology Tribe
Master Rust Conditional Compilation: From #[cfg] to cfg! with Real-World Examples

1. Syntax Description

1. #[cfg] attribute

The #[cfg] attribute can be applied to functions, modules, structs, enums, methods, etc., and decides whether the attached code is compiled based on the given condition.

Basic usage:

Only compile when the target operating system is Linux:

#[cfg(target_os = "linux")]
fn on_linux() {
    println!("This is running on Linux!");
}

Multiple conditions: Use all, any, not to combine conditions.

all: all conditions must be true.

any: any condition true.

not: condition false.

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn on_linux_x86_64() {
    println!("This is running on Linux and x86_64 architecture!");
}

#[cfg(any(target_os = "windows", target_os = "macos"))]
fn on_windows_or_mac() {
    println!("This is running on Windows or macOS!");
}

#[cfg(not(target_os = "linux"))]
fn not_on_linux() {
    println!("This is not running on Linux!");
}

2. cfg! macro

The cfg! macro evaluates a condition at compile time and returns a boolean; unlike #[cfg], it does not remove the code.

if cfg!(target_os = "linux") {
    println!("This is Linux.");
} else {
    println!("This is not Linux.");
}

3. Custom conditions

Beyond predefined conditions, you can define custom features in Cargo.toml and use them.

[features]
default = ["feature1"]   # default feature
feature1 = []            # simple feature
feature2 = []            # another feature
advanced = ["feature2"]  # advanced feature enables feature2

Use in code:

#[cfg(feature = "advanced")]
fn with_advanced_feature() {
    println!("Compiled with advanced feature");
}

Enable features via Cargo command line:

# Enable a feature
cargo run --features "feature1"

# Enable multiple features
cargo run --features "feature1 feature2"

# Enable advanced feature (also enables feature2)
cargo run --features "advanced"

# Disable default features and enable others
cargo run --no-default-features --features "feature2"

4. Conditional compilation with dependencies

You can include dependencies conditionally in Cargo.toml:

[target.'cfg(target_os = "linux")'.dependencies]
some_linux_only_crate = "0.1"

5. Conditional compilation in tests

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn linux_only_test() {
        // runs only on Linux
    }
}

6. Common cfg attributes

target_os: e.g., linux, windows, macos

target_arch: e.g., x86, x86_64, arm

target_family: unix, windows

target_env: gnu, msvc

target_endian: big, little

target_pointer_width: 32, 64

feature: enable specific feature

#[cfg(target_os = "linux")]
fn get_os_info() -> String {
    "Linux".to_string()
}
#[cfg(target_os = "windows")]
fn get_os_info() -> String {
    "Windows".to_string()
}
#[cfg(target_os = "macos")]
fn get_os_info() -> String {
    "macOS".to_string()
}
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
fn get_os_info() -> String {
    "Unknown OS".to_string()
}
fn main() {
    println!("OS: {}", get_os_info());
}

Note: Overusing conditional compilation can make code hard to maintain; encapsulate platform‑specific code behind unified interfaces.

2. Demo Example

use std::env;
use eframe::egui;

fn main() -> Result<(), eframe::Error> {
    let options = eframe::NativeOptions {
        initial_window_size: Some(egui::vec2(600.0, 400.0)),
        ..Default::default()
    };
    eframe::run_native(
        "Rust Conditional Compilation Demo",
        options,
        Box::new(|_cc| Box::new(MyApp::default())),
    )
}

struct MyApp {
    os_info: String,
    arch_info: String,
    feature_info: String,
    custom_flag_info: String,
}

impl Default for MyApp {
    fn default() -> Self {
        // OS info
        let os_info = if cfg!(target_os = "windows") {
            "Windows".to_string()
        } else if cfg!(target_os = "macos") {
            "macOS".to_string()
        } else if cfg!(target_os = "linux") {
            "Linux".to_string()
        } else {
            "未知操作系统".to_string()
        };
        // Architecture info
        let arch_info = if cfg!(target_arch = "x86_64") {
            "x86_64".to_string()
        } else if cfg!(target_arch = "aarch64") {
            "ARM64".to_string()
        } else {
            "未知架构".to_string()
        };
        // Feature flag
        let feature_info = if cfg!(feature = "advanced") {
            "启用了高级功能".to_string()
        } else {
            "使用基础功能".to_string()
        };
        // Custom flag
        let custom_flag_info = if cfg!(custom_flag = "special") {
            "特殊模式已启用".to_string()
        } else {
            "普通模式".to_string()
        };
        Self { os_info, arch_info, feature_info, custom_flag_info }
    }
}

impl eframe::App for MyApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.heading("Rust 条件编译示例");
            ui.separator();
            ui.label("这个应用程序演示了 Rust 中条件编译的不同用法。");
            ui.separator();

            ui.heading("预定义属性:");
            ui.label(format!("目标操作系统: {}", self.os_info));
            ui.label(format!("目标架构: {}", self.arch_info));
            ui.label(format!("特性标志: {}", self.feature_info));
            ui.label(format!("自定义标志: {}", self.custom_flag_info));
            ui.separator();

            ui.heading("条件编译代码示例:");
            ui.code("#[cfg(target_os = \"windows\")]
fn windows_only() {
    println!(\"这是Windows系统!\");
}");
            ui.code("#[cfg(not(target_os = \"windows\"))]
fn not_windows() {
    println!(\"这不是Windows系统!\");
}");
            ui.code("#[cfg(feature = \"advanced\")]
fn advanced_functionality() {
    println!(\"高级功能已启用!\");
}");
            ui.separator();
            ui.label("尝试使用不同的特性标志编译此程序:");
            ui.code("cargo run --features advanced");
            ui.code("cargo run --no-default-features");
        });
    }
}

// Conditional functions
#[cfg(target_os = "windows")]
fn platform_specific_function() -> String {
    "这是一个Windows特有的函数".to_string()
}
#[cfg(target_os = "macos")]
fn platform_specific_function() -> String {
    "这是一个macOS特有的函数".to_string()
}
#[cfg(target_os = "linux")]
fn platform_specific_function() -> String {
    "这是一个Linux特有的函数".to_string()
}
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
fn platform_specific_function() -> String {
    "这是其他平台特有的函数".to_string()
}

// Conditional modules
#[cfg(feature = "advanced")]
mod advanced {
    pub fn do_advanced_thing() -> String {
        "执行高级操作!".to_string()
    }
}
#[cfg(not(feature = "advanced"))]
mod advanced {
    pub fn do_advanced_thing() -> String {
        "高级功能未启用".to_string()
    }
}

This example demonstrates several Rust conditional compilation techniques: OS detection with cfg!, architecture detection, feature flag checks, conditional functions, and modules, and shows how to run the demo with Cargo.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Cross-PlatformRustCode examplesFeaturesconditional compilationCFG
Big Data Technology Tribe
Written by

Big Data Technology Tribe

Focused on computer science and cutting‑edge tech, we distill complex knowledge into clear, actionable insights. We track tech evolution, share industry trends and deep analysis, helping you keep learning, boost your technical edge, and ride the digital wave forward.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.