Nikita Fedyashev
Nikita Fedyashev

Reputation: 19048

Rust conditional compilation(cfg) with single identifier

I'm trying to understand the following example from the condition compilation manual @ doc.rust-lang.org:

// This function is only included when either foo or bar is defined
#[cfg(any(foo, bar))]
fn needs_foo_or_bar() {
  // ...
}

What do those foo and bar identifiers represent?

Is this a shortcut for target_os identifiers or what is it for?

Upvotes: 2

Views: 666

Answers (2)

Nikita Fedyashev
Nikita Fedyashev

Reputation: 19048

Turns out it had nothing to do with target_os, it is what you set in RUSTFLAGS when you build/run:

RUSTFLAGS='--cfg foo'

Which configuration options are set is determined statically during the compilation of the crate. Certain options are compiler-set based on data about the compilation. Other options are arbitrarily-set, set based on input passed to the compiler outside of the code.

Related question with a bit more advanced example

Upvotes: 1

Andrew
Andrew

Reputation: 982

From the syntax definition on the conditional compilation manual, any(foo, bar) is a ConfigurationPredicate (specifically the ConfigurationAny variation) so foo, bar is a ConfigurationPredicateList and thus foo and bar are each a ConfigurationPredicate. So you could use them to conditionally compile for a target OS. Or you could do some custom features like this:

#[cfg(any(feature = "myfeature1", feature = "myfeature2"))]
pub struct Source {
    pub email: String,
    pub name: String,
}

For more on custom features, see this question

Upvotes: 0

Related Questions