docs

#6.3. #[cfg] 條件式編譯

本頁內容

#[cfg(...)] 屬性依編譯期條件把項目納入或排除於建置之外。文法如下:

cfg_predicate   ::= identifier                              // flag
                  | identifier "=" string_lit               // key=value
                  | "all" "(" pred_list ")"
                  | "any" "(" pred_list ")"
                  | "not" "(" cfg_predicate ")"
pred_list       ::= cfg_predicate ("," cfg_predicate)* ","?
cfg_attr        ::= "#" "[" "cfg" "(" cfg_predicate ")" "]"
cfg_attr_attr   ::= "#" "[" "cfg_attr" "(" cfg_predicate ("," attr_body)+ ")" "]"
cfg_macro       ::= "cfg" "!" "(" cfg_predicate ")"

#6.3.1. 基本形式

最簡單的用法:

nabi
#[cfg(target_os = "linux")]
fn linux_specific() { ... }

#[cfg(target_arch = "x86_64")]
const HAS_AVX: bool = true;

#[cfg(test)]
mod tests { ... }

#[cfg(...)] 以一個述詞作為引數。若條件求值為真,項目就被納入編譯;若為假,就被排除。被排除的項目表現得就像從未被寫出一樣,因此其他程式碼的名稱解析也看不到它。

#6.3.2. 述詞的種類

#key = value

以鍵與值配對表達的條件。

nabi
#[cfg(target_os = "linux")]
#[cfg(target_arch = "x86_64")]
#[cfg(target_pointer_width = "64")]
#[cfg(feature = "gpu")]

標準的鍵如下:

鍵可能的值
target_arch"x86_64"、"aarch64"、"x86"、"arm"、"wasm32"、"riscv64"、"riscv32"、"powerpc64"、"s390x"
target_os"linux"、"android"、"macos"、"ios"、"windows"、"freebsd"、"wasi"、"unknown"、"none"
target_pointer_width"64"、"32"
target_endian"little"、"big"
target_family"unix"、"windows"、"wasm"
target_env"gnu"、"musl"、"msvc"
target_abi"sim"(Apple 模擬器:aarch64-apple-ios-sim)
feature使用者定義。由命令列或套件管理器設定

目標沒有 target_family / target_env / target_abi 時,這些鍵不存在。

所有 target_* 鍵都跟隨建置的 --target(9.1.2)。沒有 --target 時,適用主機目標。

#單純的旗標

也有只有鍵而沒有值的布林旗標形式。

nabi
#[cfg(test)]                 // only in test builds
#[cfg(debug_assertions)]      // only in debug builds

#組合子

要組合多個條件,請使用組合子。

nabi
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[cfg(not(target_os = "windows"))]

各組合子的意義:

組合子意義
all(...)每個引數都為真
any(...)至少一個為真
not(...)引數為假

組合子可以自由巢狀。

nabi
#[cfg(all(
    target_os = "linux",
    any(target_arch = "x86_64", target_arch = "aarch64"),
    not(feature = "minimal"),
))]
fn linux_native() { ... }

#6.3.3. 附加位置

#[cfg] 適用於項目、欄位(具名、元組、聯集、變體與元組變體的欄位)、列舉變體、trait、impl 或 extern 區塊中的項目、陳述式、match 分支、結構字面值欄位與函式參數。cfg 為假的參數會從簽章中移除;呼叫傳入其餘參數的引數。閉包參數不接受屬性。

nabi
#[cfg(...)] fn f() { ... }
#[cfg(...)] struct S { ... }
#[cfg(...)] mod m { ... }
#[cfg(...)] use foo::bar;
#[cfg(...)] static X: i32 = 0;

struct Foo {
    #[cfg(target_pointer_width = "64")]
    big_field: u64;                              // exists only on 64-bit
}

fn run(op: Op) {
    #[cfg(test)] check();                        // statement
    match op {
        Op::Add => add(),
        #[cfg(debug_assertions)]
        Op::Trace => trace(),                    // match arm
        _ => {},
    }
}

若條件為假,該項目被視為不存在:它在剖析之後、derive 與其他屬性看到它之前就被移除(6.3.7)。元區塊展開的輸出以建置的 cfg 剖析,因此其中的 #[cfg] 以相同方式適用。

#6.3.4. #[cfg_attr(...)] 有條件的其他屬性

#[cfg_attr] 有條件地附加另一個屬性。

nabi
#[cfg_attr(target_os = "windows", link("kernel32"))]
extern "C" { ... }

#[cfg_attr(test, derive(Debug))]
struct S { ... }

形式是 cfg_attr(condition, attribute_to_apply);若條件為真,其後的屬性就表現得像直接附加一樣。在第一個範例中,#[link("kernel32")] 只在 Windows 建置中適用;在第二個範例中,#[derive(Debug)] 只在測試建置中適用。

可以一次套用多個屬性。

nabi
#[cfg_attr(test, derive(Debug), allow(unused))]
struct S { ... }

#6.3.5. cfg!(...) 編譯期的 bool 值

cfg!(...) 出現在運算式位置,在編譯期求值為 bool。

nabi
const IS_LINUX: bool = cfg!(target_os = "linux");

if cfg!(feature = "gpu") {
    use_gpu()
} else {
    use_cpu()
}

它接受與 #[cfg] 相同的述詞,其結果是 const 意義上的 const 運算式,因此也可以用在其他 const 位置。cfg! 與 include_str! / include_bytes!(6.11)一樣,是編譯器的內建形式,而不是巨集(由呼叫觸發的 meta 定義,6.8.12):它固定於編譯器中,不能被重新定義或遮蔽,其名稱是保留的。

#[cfg] 與 cfg!() 的差異:

  • #[cfg]:把整個項目納入或排除於建置之外。
  • cfg!():看起來像執行時的分支,但實際上是編譯期常數,因此其中一個分支會被無用程式碼消除移除。
nabi
// #[cfg]: only one of the two functions is compiled
#[cfg(feature = "gpu")] fn run() { use_gpu() }
#[cfg(not(feature = "gpu"))] fn run() { use_cpu() }

// cfg!(): branch within one function; the compiler removes one side
fn run() {
    if cfg!(feature = "gpu") { use_gpu() } else { use_cpu() }
}

請依方便性與程式碼結構在兩種形式之間選擇。

#6.3.6. 參數的來源

#target_* 鍵

target_* 鍵依建置的目標平台自動設定。它們對平台目標中的每個支援目標都有明確定義的值。值 "riscv64"、"riscv32"、"powerpc64"、"s390x" 與 target_os = "none" 只來自進行中的目標(0.6.2)。

#feature 鍵

feature 鍵由命令列選項,或由套件管理器與建置工具設定。

bash
nabic build --cfg feature=gpu

套件管理器 nabi 依套件設定它:每個套件都以 feature = "<f>" 編譯,恰好對應建置為它啟用的那些功能特性(9.10.4c)。nabic --cfg feature=<f> 只設定正在編譯之套件的功能特性;相依套件的功能特性以 --extern-feature <name>=<f> 給出(9.1),而標準函式庫沒有功能特性。

#test / debug_assertions

這兩個旗標由建置模式決定。

  • test:以 nabic test 或等價指令建置時為真。
  • debug_assertions:在 -O0 時為真。

#6.3.7. 何時求值

#[cfg] 在剖析之後立即求值。條件為假的項目立即從 AST 中移除,之後的階段(名稱解析、型別檢查、程式碼產生)只看到剩下的 AST。

編譯器會記住它移除的名稱及其條件。當方法、自由函式、型別或模組的查找(或匯入)失敗,而有某個被移除的項目具有該名稱時,錯誤訊息會說明它存在於何處:

error[E0046]: no method `pidfd` found for type `Child`
  --> src/main.nabi:4:13
   |
 4 |     let p = c.pidfd();
   |             ^^^^^^^^^
   |
   = help: `Child` is a standard type; call one of its methods, such as `id`, `into`, `kill`, `fmt`, `handle`, `wait`
   = note: `pidfd` is only available when its `cfg` holds (`#[cfg(any(target_os = "linux", target_os = "android"))]`)
   = help: put the code that uses it under the same `#[cfg(any(target_os = "linux", target_os = "android"))]`

這發生在 meta 展開階段(樣板記號與展開)之前,因此附加在 cfg 為假之項目上的使用者定義 derive 與屬性也不會被處理。

#6.3.8. 否定 / 衝突的 cfg

若在同一個建置中多個條件同時為真,使兩個定義都留下來,就會發生一般的重複定義錯誤。

nabi
#[cfg(target_os = "linux")]
fn impl_a() { ... }

#[cfg(target_os = "linux")]    // same cfg + same name → conflict
fn impl_a() { ... }            // ERROR: both definitions exist in the same build

下列則沒有問題,因為兩個 cfg 互斥,在任何建置中只有一個定義是有效的。

nabi
#[cfg(target_os = "linux")]
fn impl_a() { ... }

#[cfg(not(target_os = "linux"))]
fn impl_a() { ... }            // OK: the two cfgs are mutually exclusive

#6.3.9. cfg 與模組 / 檔案

cfg 可以附加在整個模組上。

nabi
#[cfg(target_os = "linux")]
mod linux_only {
    // this whole module exists only in Linux builds
}

模組的檔案與目錄仍存在於磁碟上,但若 cfg 為假,它們不會被讀取,或在讀取後立即被捨棄。

#6.3.10. cfg 內的巨集(無)

cfg 述詞內不能出現任意運算式或巨集呼叫。只允許固定的鍵值形式與組合子。

#[cfg(custom_macro!())]                // not adopted

#6.3.11. 偵錯工具

nabic --print cfg 印出建置中有效的 cfg 值:--target 的目標鍵、--cfg 旗標,以及低於 -O1 時的 debug_assertions(9.1.3)。

發現錯誤? 在 GitHub 上編輯此頁 最後更新: