Confusion on cfg semantics

I'm confused about the semantics of cfg.

Reading: Conditional compilation - The Rust Reference I see that the parameter to cfg can be (among other things):

A configuration option. It is true if the option is set and false if it is unset.

However, in the below code, the "target_family" parameter is apparently both set (with the value "unix") and not set -- both target_family = "unix" and not(target_family) evaluate to true.

Clearly I'm missing something, but I've had a hard time getting google to show me what it is. I suspect that there are different kinds of configuration options, those that can be set and those that can have values, but that is a less intuitive design than I've grown to expect from rust, so I don't trust that conclusion.

Is there any documentation that is more explicit about this that you can point me to?

Thank you!



fn main() {
    #[cfg(target_family)]
    println!("target_family defined");
    
    #[cfg(target_family="unix")]
    println!("target_family is unix");
    
    #[cfg(not(target_family))]
    println!("target_family not defined");
}

(Playground)

Output:

target_family is unix
target_family not defined

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 0.56s
     Running `target/debug/playground`

Edit: to be clear, this isn't actually because I want to check if target_family exists, but for other attributes that might or might not be defined in my build system: I just couldn't figure out how to set any attributes in the rust playground.

target_family="unix" is its own option independent from target_family.

You can set both my_cfg and my_cfg="whatever" as cfg options but neither influences whether the other is set. Generally I would avoid having my_cfg mean something if you also have my_cfg="whatever" because it can be confusing to anyone reading your code.

4 Likes

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.