Conditional compilation with customized feature

Hi there, I got a problem when using the conditional feature in my rust project, plz help:)

In my Cargo.tom file:

[features]
default = []
enable-debug = ["cortex-m-semihosting"]
enable-pac = ["stm32f4"]
enable-hal = ["stm32f4xx-hal"]

[dependencies]
cortex-m = "0.6.0"
cortex-m-rt = "0.6.10"
# panic-halt = "0.2.0"

# For debugging purpose, enable `exit` feature
panic-semihosting = { version = "0.5.3", features = ['exit'] }

# Print debug info to host console, optional
cortex-m-semihosting = { version = "0.3.3", optional = true }

# PAC (Peripheral Access Crate), optional
stm32f4 = { version = "0.11.0", features = ["stm32f407", "rt"], optional = true }

# HAL (Hardware Abstraction Layer), optional
stm32f4xx-hal = { version = "0.8.3", features = ['stm32f407'], optional = true }

In my main.rs I got this:

#![allow(warnings)]
#![no_std]
#![no_main]

use cortex_m::peripheral::Peripherals;
use cortex_m_rt::entry;

#[cfg(feature = "enable-debug")]
use cortex_m_semihosting::{dbg, hprintln};

use panic_semihosting as _;

#[entry]
fn main() -> ! {
    if cfg!(feature = "enable-debug") {
        let _ = hprintln!("Basic STM32F4 demo is running >>>>>");
    }

    // Get the singleton `Peripherals` instance. This method can only
    // successfully called **once()**, that's why return an `Option`.
    let peripherals = Peripherals::take().unwrap();

    // You can't do this, as `cortex_m::Peripherals` cannot be formatted
    // using `{:?}` because it doesn't implement `core::fmt::Debug`.
    // dbg!(peripherals);

    let x = 10;
    if cfg!(feature = "enable-debug") {
        hprintln!("x is {}", x);
        dbg!(x);
    }

    // This will panic!!!
    assert_eq!(x, 8);

    loop {
        // Your program loop code here
    }
}

Then when I build with this, it works:

cargo build --release --features "enable-debug"

But when I remove the --features "enable-debug" part which I want a production mode build, but it reports error below:

cargo build --bin basic --release

error: cannot find macro `hprintln` in this scope
  --> src/bin/basic.rs:30:17
   |
30 |         let _ = hprintln!("Basic STM32F4 demo is running >>>>>");
   |                 ^^^^^^^^

error: cannot find macro `hprintln` in this scope
  --> src/bin/basic.rs:43:9
   |
43 |         hprintln!("x is {}", x);
   |         ^^^^^^^^

error: cannot find macro `dbg` in this scope
  --> src/bin/basic.rs:44:9
   |
44 |         dbg!(x);
   |         ^^^

error: aborting due to 3 previous errors

For my understanding, it should work as just not include the if block at all, have no idea how to get around this....:slight_smile:

Use this syntax instead:

#[cfg(feature = "enable-debug")]
let _ = hprintln!("Basic STM32F4 demo is running >>>>>");

The syntax you're using now just results in a boolean, you want to actually not compile the pieces at all.

2 Likes