cfg

Conditional compilation is possible through two different operators:

  • the cfg attribute: #[cfg(...)] in attribute position
  • the cfg! macro: cfg!(...) in boolean expressions

Both utilize identical argument syntax.

  1. // This function only gets compiled if the target OS is linux
  2. #[cfg(target_os = "linux")]
  3. fn are_you_on_linux() {
  4. println!("You are running linux!");
  5. }
  6. // And this function only gets compiled if the target OS is *not* linux
  7. #[cfg(not(target_os = "linux"))]
  8. fn are_you_on_linux() {
  9. println!("You are *not* running linux!");
  10. }
  11. fn main() {
  12. are_you_on_linux();
  13. println!("Are you sure?");
  14. if cfg!(target_os = "linux") {
  15. println!("Yes. It's definitely linux!");
  16. } else {
  17. println!("Yes. It's definitely *not* linux!");
  18. }
  19. }

See also:

the reference, cfg!, and macros.