简体   繁体   中英

How do I create a Rust function or macro for debugging that gets optimized away in a release build?

In a debug build, I want to check for OpenGL errors after almost every OpenGL call to ease debugging. As this is a costly operation, I don't want to do it in a release build. Right now I'm using functions like:

pub fn debug_panic_on_errors() {
    if cfg!(debug_assertions) {
        get_errors().unwrap();
    }
}

Am I correct in assuming that this method will always be optimized away completely? Is there a better, more future-proof way?

In release mode the function will be expanded to if false { … } which is very trivial to optimize away, so yes you could just use it as-is.


If you are being paranoid you could #[cfg] two functions like

#[cfg(debug_assertions)]
pub fn debug_panic_on_errors() { 
    get_errors().unwrap();
}

#[cfg(not(debug_assertions))]
pub fn debug_panic_on_errors() {
}

so that the outcome is chosen during parsing, to ensure we don't rely on the optimizer. But I don't really recommend this...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM