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

With the C preprocessor, this is usually done,

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

Cargo gross equivalents:

  • cargo build --release for release.
  • cargo build for debugging.

How to use Rust #[cfg(...)] attribute or cfg!(...) macro to do something like this?

I understand that the Rust preprocessor does not work like C. I checked the documentation and some attributes are listed on this page . (assuming this list is complete)

debug_assertions can be checked, but it can be misleading when used to check for a more general debugging case.

I am not sure whether this issue should be related to Cargo or not.

+18
source share
1 answer

You can use debug_assertions as the corresponding configuration flag. It works both with the attributes #[cfg(...)] and with 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 has been named as the correct way to do this in this discussion . No more suitable built-in conditions.

From the link :

debug_assertions - debug_assertions by default when compiling without optimization. This can be used to include additional debugging code in development, but not in production. For example, it controls the behavior of the standard debug_assert! library debug_assert! macro.

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

+27
source

All Articles