Rust conditional compilation (#[cfg(...)]) with names instead of hard-coded strings?

194 views Asked by At

I'd like to use Rust's conditional compilation, e.g.:

#[cfg(platform="value")]

I'm wondering if there's a way to define a constant VALUE = "value", such that this can be written as

#[cfg(platform=VALUE)]

As I understand it, I'd need these defined during my build script exec (before compiling the module), but still accessible within cfg macros within these files.

Is there a way to do this?

Alternatively, any thoughts on an approach that's cleaner than hard-coding the same string repeatedly (and risking typos)?

1

There are 1 answers

0
Chayim Friedman On

This is not possible.

However, the Rust developers are aware that cfgs are error-prone, and have developed an accepted (and implemented) RFC to help prevent that. With this RFC, the compiler warns about unknown cfg values (or names).

Cargo also has unstable support for this feature. To use it, you need to enable the -Zcheck-cfg option in the command line invocation of Cargo. It accepts four values:

  • features for checking of features cfgs.
  • names for checking of well-known cfg names.
  • values for checking of well-known cfg values.
  • output for checking of custom cfgs from build scripts.

To use all checks, pass -Zcheck-cfg=features,names,values,output in the command line.

If you have a build scripts outputting custom cfgs, you need to enable -Zcheck-cfg=output as well as adjust your build scripts to output cargo:rustc-check-cfg instructions. They work like the following:

println!("cargo:rustc-check-cfg=names(platform)");
println!(r#"cargo:rustc-check-cfg=values(platform, "value", "value2")"#);