Rust compiles conditionally in cargo

Time:2021-3-4

explain

stayRust conditional compilationIn, we briefly introduced conditional compilation, but in the example, we did not show how to compile with cargo. Next, we will introduce how to compile with cargo.

Source code

//src/main.rs
#[cfg(some_condition)]
fn conditional_function() {
    println!("condition met!");
}

fn main() {
    conditional_function();
    println!("Hello, world!");
}

Cargo.toml file

stay cargo.toml Add the following to the list:

[features]
some_condition = []

compile

If you directly compile: Cargo build, you will find an error.

The correct way to compile is as follows:

cargo build --features some_condition

This work adoptsCC agreementReprint must indicate the author and the link of this article

Linghu Yichong