Conditional compilation ("if defs")

Hello.
How to use conditional-compilation in Rust?

if cfg!(option)
{
      println!("Option 1");
}
else
{
      println!("Option 2");
}

cargo build --option

Do you have a specific question regarding conditional compilation, or are you just seeking general information? The language reference contains some useful general info: https://doc.rust-lang.org/reference/conditional-compilation.html

Yes. I don't understand how to pass my option to cargo build.

The "option" you're showing for cargo build is usually done with features: https://doc.rust-lang.org/cargo/reference/features.html

#[cfg(feature = "foo")]
{
    println!("Hello, world!");
}

cargo build --features foo

1 Like

@parasyte

if cfg!(feature = "foo")]
{
    println!("Option1");
}
else {
    println!("Option2");
}

??

If you remove the stray ], that should work. You'll need to define the feature in Cargo.toml as well:

[features]
foo = []

Then building with and without the foo feature results in different output:

$ cargo run --features foo
   Compiling wat v0.1.0 (/Volumes/code/misc/feat)
    Finished dev [unoptimized + debuginfo] target(s) in 0.79s
     Running `target/debug/feat`
Option1
$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/feat`
Option2

my src/main.rs looks like:

fn main() {
    if cfg!(feature = "foo") {
        println!("Option1");
    } else {
        println!("Option2");
    }
}

I don't think that code will be compiled out though. I don't think rust can compile out if statements right now. I think @parasyte is more correct. I believe if you wanted to do a compile time if else you need to have two blocks that are conditionally on the opposite thing.

Here is an example https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e41a2813ef0bae5f4cf714de1907c9a4

Note that you don't have to use a block you can use any expression.

LLVM does almost all of the optimization passes, including dead code elimination, which can remove unused conditional branches: https://rust.godbolt.org/z/i9Pvsz

1 Like

That is a very cool tool. Thanks for sharing.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.