Hello.
How to use conditional-compilation in Rust?
if cfg!(option)
{
println!("Option 1");
}
else
{
println!("Option 2");
}
cargo build --option
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: Conditional compilation - The Rust Reference
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
: Features - The Cargo Book
#[cfg(feature = "foo")]
{
println!("Hello, world!");
}
cargo build --features foo
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 Rust Playground
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: Compiler Explorer
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.