'select code based on cfg attribute not true [rust]
I want to 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 func1 when compiling for debug build (i.e. option --release is not passed to command cargo build).
#[cfg(debug_assertions)]
pub fn func1() -> String {
String::from("debug")
}
In this case, I want a "release version" of the function,
#[cfg(debug_assertions)]
pub fn func1() -> String {
String::from("debug")
}
#[!cfg(debug_assertions)]
pub fn func1() -> 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")]
Solution 1:[1]
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.
Solution 2:[2]
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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Sergio Ribera |
