I want rust code compiled when the compilation attribute debug_assertions is false (or not enabled), i.e. a "debug build".
Is this possible? What is the syntax?
For example, I can compile function build_type when compiling for debug build (i.e. option --release is not passed to command cargo build).
#[cfg(debug_assertions)]
pub fn build_type() -> String {
String::from("debug")
}
In this case, I want a "release version" of the function,
#[cfg(debug_assertions)]
pub fn build_type() -> String {
String::from("debug")
}
#[!cfg(debug_assertions)]
pub fn build_type() -> String {
String::from("release")
}
However, the syntax #[!cfg(debug_assertions)] results in cargo build error expected identifier, found '!'.
Other failed syntax variations were:
#[cfg(!debug_assertions)]#[cfg(debug_assertions = false)]#[cfg(debug_assertions = "false")]In book Rust By Example, the section on cfg has this snipped code sample:
// 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!");
}
Use syntax #[cfg(not(debug_assertions))] to conditionally compile for cargo build --release.
The book The Rust Reference has the full list of conditional compilation predicates.
You can do this, based on rust book
if cfg!(not(target_os = "linux")) {
// Your code
} else {
// Your else code
}
And to check if it is a debug binary, you can do the same, but with the debug_assertions cfg, like this
if cfg!(debug_assertions) {
// Your code if is debug
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With