3

In Rust, it's possible to perform conditional compilation as follows.

#[cfg(rust_version = "1.10")]
fn my_func() {}

Is it possible to define variables for cfg to check within the same source file?

For example:

// leave off, just a quick test to enable when troubleshooting.
#define use_counter 1  // C style (not valid Rust)

#[cfg(use_counter == "1")]
static mut fn_counter: usize = 0;

fn my_func() {

#[cfg(use_counter = "1")]
    unsafe { fn_counter += 1; }

}

main () {
    // code calling 'my_func'

    // print how many times the function is called.
#[cfg(use_counter = "1")]
    unsafe { println!("Function count {}", fn_counter); }

}

I'm not asking how to write a function counter, it's just an example of optionally inserting logic into a source file.

Community
  • 1
  • 1
ideasman42
  • 42,413
  • 44
  • 197
  • 320
  • What's wrong with specifying the configuration via Cargo or the rustc command line? – Shepmaster Aug 13 '16 at 03:58
  • Using cargo is fine for developer visible build options, In this case I just want a switch which is local to the file I can use for performing some extensive tests *(which isn't enabled by default, or exposed at the crate level)* – ideasman42 Aug 13 '16 at 04:19
  • 3
    I wish `#[cfg(rust_version)]` were actually a thing... – durka42 Aug 19 '16 at 21:13

1 Answers1

1

Yes, this is written as #[cfg(use_counter)]. Such flags can be enabled or disabled on the command line at compile time and are not exposed in Cargo.toml.

fn main() {
    #[cfg(use_counter)]
    println!("counter is enabled");
}

Using Cargo, run with the feature disabled:

$ cargo run

Using Cargo, run with the feature enabled:

$ RUSTFLAGS="--cfg use_counter" cargo run

Compile directly with the feature disabled:

$ rustc src/main.rs

Compile with the feature enabled:

$ rustc src/main.rs --cfg use_counter
dtolnay
  • 9,621
  • 5
  • 41
  • 62
  • I suspect the answer should be ‘no’, because the question asks for per-file option and this is still per-build, though not written out to Cargo.toml. – Jan Hudec Oct 08 '18 at 06:57
  • I'd agree with @JanHudec — this doesn't *define* a config setting *within a source file*, as the title indicates. – Shepmaster Oct 08 '18 at 12:59
  • I believe this answers the use case in the question. The answer is that flags *don't need to be declared*, i.e. there is nothing like `#![declare_flag(use_counter, default = 0)]`. You can just use them straight away. They are not enabled by default, as the question wanted, and not exposed in Cargo.toml to downstream crates, which is my interpretation of "not exposed at the crate level" i.e. at the level of the crate's API. If you want a flag local to a source file then simply don't use the same flag in other source files. – dtolnay Oct 08 '18 at 16:00