# 條件編譯
> [conditional-compilation.md](https://github.com/rust-lang/rust/blob/master/src/doc/book/conditional-compilation.md)
commit 024aa9a345e92aa1926517c4d9b16bd83e74c10d
Rust有一個特殊的屬性,`#[cfg]`,它允許你基于一個傳遞給編譯器的標記編譯代碼。它有兩種形式:
~~~
#[cfg(foo)]
# fn foo() {}
#[cfg(bar = "baz")]
# fn bar() {}
~~~
它還有一些幫助選項:
~~~
#[cfg(any(unix, windows))]
# fn foo() {}
#[cfg(all(unix, target_pointer_width = "32"))]
# fn bar() {}
#[cfg(not(foo))]
# fn not_foo() {}
~~~
這些選項可以任意嵌套:
~~~
#[cfg(any(not(unix), all(target_os="macos", target_arch = "powerpc")))]
# fn foo() {}
~~~
至于如何啟用和禁用這些開關,如果你使用Cargo的話,它們可以在你`Cargo.toml`中的[`[features]`部分](http://doc.crates.io/manifest.html#the-%5Bfeatures%5D-section)設置:
~~~
[features]
# no features by default
default = []
# The “secure-password” feature depends on the bcrypt package.
secure-password = ["bcrypt"]
~~~
當你這么做的時候,Cargo傳遞給`rustc`一個標記:
~~~
--cfg feature="${feature_name}"
~~~
這些`cfg`標記集合會決定哪些功能被啟用,并且因此,哪些代碼會被編譯。讓我們看看這些代碼:
~~~
#[cfg(feature = "foo")]
mod foo {
}
~~~
如果你用`cargo build --features "foo"`編譯,他會向`rustc`傳遞`--cfg feature="foo"`標記,并且輸出中將會包含`mod foo`。如果我們使用常規的`cargo build`編譯,則不會傳遞額外的標記,因此,(輸出)不會存在`foo`模塊。
### cfg_attr
你也可以通過一個基于`cfg`變量的`cfg_attr`來設置另一個屬性:
~~~
#[cfg_attr(a, b)]
# fn foo() {}
~~~
如果`a`通過`cfg`屬性設置了的話這與`#[b]`相同,否則不起作用。
# cfg!
`cfg!`[語法擴展](#)也讓你可以在你的代碼中使用這類標記:
~~~
if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
println!("Think Different!");
}
~~~
這會在編譯時被替換為一個`true`或`false`,依配置設定而定。
- 前言
- 貢獻者
- 1.介紹
- 2.準備
- 3.學習 Rust
- 3.1.猜猜看
- 3.2.哲學家就餐問題
- 3.3.其它語言中的 Rust
- 4.語法和語義
- 4.1.變量綁定
- 4.2.函數
- 4.3.原生類型
- 4.4.注釋
- 4.5.If語句
- 4.6.循環
- 4.7.所有權
- 4.8.引用和借用
- 4.9.生命周期
- 4.10.可變性
- 4.11.結構體
- 4.12.枚舉
- 4.13.匹配
- 4.14.模式
- 4.15.方法語法
- 4.16.Vectors
- 4.17.字符串
- 4.18.泛型
- 4.19.Traits
- 4.20.Drop
- 4.21.if let
- 4.22.trait 對象
- 4.23.閉包
- 4.24.通用函數調用語法
- 4.25.crate 和模塊
- 4.26.const和static
- 4.27.屬性
- 4.28.type別名
- 4.29.類型轉換
- 4.30.關聯類型
- 4.31.不定長類型
- 4.32.運算符和重載
- 4.33.Deref強制多態
- 4.34.宏
- 4.35.裸指針
- 4.36.不安全代碼
- 5.高效 Rust
- 5.1.棧和堆
- 5.2.測試
- 5.3.條件編譯
- 5.4.文檔
- 5.5.迭代器
- 5.6.并發
- 5.7.錯誤處理
- 5.8.選擇你的保證
- 5.9.外部函數接口
- 5.10.Borrow 和 AsRef
- 5.11.發布途徑
- 5.12.不使用標準庫
- 6.Rust 開發版
- 6.1.編譯器插件
- 6.2.內聯匯編
- 6.4.固有功能
- 6.5.語言項
- 6.6.鏈接進階
- 6.7.基準測試
- 6.8.裝箱語法和模式
- 6.9.切片模式
- 6.10.關聯常量
- 6.11.自定義內存分配器
- 7.詞匯表
- 8.語法索引
- 9.參考文獻
- 附錄:名詞中英文對照