Kconfig 是 Linux 核心配置系統的描述語言,定義配置選項的類型、相依關係、顯示邏輯與選單結構。本文系統解析 Kconfig 語法規則,包含選項類型、屬性關鍵字、依賴運算邏輯與選單階層建立機制。
config MODULE_SIG
bool "Module signature verification"
depends on MODULES
help
Enable module signature verification to increase kernel security.
Modules without valid signatures will be rejected.
config 關鍵字定義新選項| 關鍵字 | 基礎類型 | 說明 | 範例值 |
|---|---|---|---|
| bool | tristate | 布林值 (y/n) | y, n |
| tristate | tristate | 三態 (內建/模組/不選) | y, m, n |
| string | string | 字串 | "text" |
| hex | string | 十六進制數 | 0x1F |
| int | string | 整數 | 1024 |
所有類型最終映射到 tristate (y/m/n) 或 string 兩種基礎儲存類型。
類型定義可內建 prompt:
# 等價寫法
bool "Networking support"
# 等同於
bool
prompt "Networking support"
prompt "Prompt text" [if ]
if 條件控制顯示
default [if ]
depends on
# 或
requires
&& 邏輯
select [if ]
range [if ]
help
Multi-line help text...
Indentation determines end of help block.
# 或
---help---
Help text...
運算式語法 (優先級由高到低):
| 語法 | 說明 | 範例 |
|---|---|---|
| 符號值 (bool/tristate 直接用值,其他類型視為 n) | DEBUG |
| 相等比較 | ARCH = "arm" |
| 不等比較 | DEBUG != n |
( | 分組改變優先級 | (DEBUG && VERBOSE) |
! | 邏輯非 | !EXPERT |
| 邏輯與 (取最小值: n < m < y) | DEBUG && VERBOSE |
| 邏輯或 (取最大值) | ARM || ARM64 |
表達式值為 m 或 y 時選項可見/可選;n 時隱藏/強制關閉。
menu "Network device support"
depends on NET
config NETDEVICES
bool "Network device support"
default y
config DUMMY
tristate "Dummy net driver support"
endmenu
menu ... endmenu 定義選單區塊depends on若選項 B depends on 選項 A,且 A 為 bool/tristate 類型,B 自動成為 A 的子選單。需滿足:
config ADVANCED_OPTION
bool "Advanced tuning"
depends on EXPERT # 僅專家模式可見
config BLK_DEV_LOOP
tristate "Loopback device support"
default m if BLOCK # 區塊裝置啟用時預設為模組
config VIRTUALIZATION
bool "Virtualization support"
select KVM
select VHOST_NET
config CPU_FREQ_GOV_PERFORMANCE
bool "Performance governor"
prompt "Performance governor" if CPU_FREQ
make menuconfig 讀取 arch/$(ARCH)/Kconfig 遞歸 source 子目錄 Kconfig.config (含 CONFIG_XXX=y/m/n).config 變數決定編譯目標 (obj-y/obj-m)include/generated/autoconf.h 提供 CONFIG_XXX 宏供 C 代碼使用