• rust 条件编译


    条件编译可以通过两种不同的操作符实现,如下:
    
    -   cfg属性:在属性位置中使用#[cfg(...)]
    
    -   cfg!宏:在布尔表达式中使用cfg!(...)
     

    Configuration conditional checks are possible through two different operators:

    • the cfg attribute: #[cfg(...)] in attribute position
    • the cfg! macro: cfg!(...) in boolean expressions

    While the former enables conditional compilation, the latter conditionally evaluates to true or false literals allowing for checks at run-time. Both utilize identical argument syntax.

    // This function only gets compiled if the target OS is linux
    #[cfg(target_os = "linux")]
    fn are_you_on_linux() {
        println!("You are running linux!");
    }
    
    // And this function only gets compiled if the target OS is *not* linux
    #[cfg(not(target_os = "linux"))]
    fn are_you_on_linux() {
        println!("You are *not* running linux!");
    }
    
    fn main() {
        are_you_on_linux();
    
        println!("Are you sure?");
        if cfg!(target_os = "linux") {
            println!("Yes. It's definitely linux!");
        } else {
            println!("Yes. It's definitely *not* linux!");
        }
    }
    [root@bogon cfg]# ls
    Cargo.lock  Cargo.toml  README.md  src
    [root@bogon cfg]# cargo build
       Compiling hello_world v0.1.0 (/data2/rust/cfg)
        Finished dev [unoptimized + debuginfo] target(s) in 0.39s
    [root@bogon cfg]# cargo run
        Finished dev [unoptimized + debuginfo] target(s) in 0.01s
         Running `target/debug/hello_world`
    You are running linux!
    Are you sure?
    Yes. It's definitely linux!
    [root@bogon cfg]# 
    //main.rs
    #[cfg(some_condition)]
    fn conditional_function() {
        println!("condition met!");
    }
    
    fn main() {
        conditional_function();
        println!("Hello, world!");
    }
    
     
    [root@bogon src]# rustc --cfg some_condition main.rs
    [root@bogon src]# ./main
    condition met!
    Hello, world!
    [root@bogon src]# rustc  main.rs
    error[E0425]: cannot find function `conditional_function` in this scope
     --> main.rs:8:5
      |
    8 |     conditional_function();
      |     ^^^^^^^^^^^^^^^^^^^^ not found in this scope
    
    error: aborting due to previous error
    
    For more information about this error, try `rustc --explain E0425`.
    [root@bogon src]#
  • 相关阅读:
    中台架构的新一代业务支撑体系是如何实现
    共同探索企业级数据库架构之道路
    综述:图像风格化算法最全盘点 | 内附大量扩展应用
    【加法笔记系列】JS 加法器模拟
    OAuth 及 移动端鉴权调研
    神经引导演绎搜索:两全其美的程序合成方法
    围观神龙架构首次开箱,现场直播暴力拆机
    QA质量意识
    接口测试总结篇
    接口测试用例设计
  • 原文地址:https://www.cnblogs.com/dream397/p/14229765.html
Copyright © 2020-2023  润新知