How to check release / debug builds using cfg in Rust?

前端 未结 1 1071
一向
一向 2021-02-04 23:09

With the C pre-processor it\'s common to do,

#if defined(NDEBUG)
    // release build
#endif

#if defined(DEBUG)
    // debug build
#endif

Carg

相关标签:
1条回答
  • 2021-02-04 23:45

    You can use debug_assertions as the appropriate configuration flag. It works with both #[cfg(...)] attributes and the cfg! macro:

    #[cfg(debug_assertions)]
    fn example() {
        println!("Debugging enabled");
    }
    
    #[cfg(not(debug_assertions))]
    fn example() {
        println!("Debugging disabled");
    }
    
    fn main() {
        if cfg!(debug_assertions) {
            println!("Debugging enabled");
        } else {
            println!("Debugging disabled");
        }
    
        #[cfg(debug_assertions)]
        println!("Debugging enabled");
    
        #[cfg(not(debug_assertions))]
        println!("Debugging disabled");
    
        example();
    }
    

    This configuration flag was named as a correct way to do this in this discussion. There is no more suitable built-in condition for now.

    From the reference:

    debug_assertions - Enabled by default when compiling without optimizations. This can be used to enable extra debugging code in development but not in production. For example, it controls the behavior of the standard library's debug_assert! macro.

    An alternative, slightly more complicated way, is to use #[cfg(feature = "debug")] and create a build script that enables a "debug" feature for your crate, as shown here.

    0 讨论(0)
提交回复
热议问题