#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. 基本形式
最简单的用法:
#[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
把键与值配对来表达的条件。
#[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 时,采用主机目标。
#普通标志
还有一种只有键、没有值的布尔标志形式。
#[cfg(test)] // only in test builds
#[cfg(debug_assertions)] // only in debug builds
#组合子
要组合多个条件,使用组合子。
#[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(...) | 实参为假 |
组合子可以自由嵌套。
#[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 为假的参数从签名中移除;调用只传递其余参数的实参。闭包参数不接受属性。
#[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] 有条件地附着另一个属性。
#[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)] 只在测试构建中生效。
可以一次应用多个属性。
#[cfg_attr(test, derive(Debug), allow(unused))]
struct S { ... }
#6.3.5. cfg!(...) 编译期 bool 值
cfg!(...) 出现在表达式位置,在编译期求值为一个 bool。
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)一样,是编译器内置形式,而不是宏(由调用触发的元定义,6.8.12):它固定在编译器中,不能被重新定义或遮蔽,其名称是保留的。
#[cfg] 与 cfg!() 的区别:
#[cfg]:把整个项纳入构建或从构建中排除。cfg!():看起来像运行时分支,实际上是编译期常量,因此有一个分支会被死代码消除去掉。
// #[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 键由命令行选项或包管理器与构建工具设置。
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"))]`
这一步在元展开阶段(模板记号与展开)之前,因此附着在 cfg 为假的项上的用户定义 derive 和属性也不会被处理。
#6.3.8. 取反 / 冲突的 cfg
如果在同一次构建中多个条件同时为真,两个定义都保留下来,就会产生普通的重复定义错误。
#[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 互斥,任何一次构建中只有一个定义有效。
#[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 可以附着在整个模块上。
#[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 上编辑此页 最后更新: