Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux Kconfig 語法完整解析:選項定義、屬性、依賴關係與選單結構

編輯:Linux 教學

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 關鍵字定義新選項
  • 選項名稱慣用大寫字母、數字、底線
  • 後續縮排行定義屬性 (type、prompt、depends、default、help 等)
  • 同名選項可重複定義,但類型不可衝突

二、選項類型定義 (Type Definition)

關鍵字基礎類型說明範例值
booltristate布林值 (y/n)y, n
tristatetristate三態 (內建/模組/不選)y, m, n
stringstring字串"text"
hexstring十六進制數0x1F
intstring整數1024

所有類型最終映射到 tristate (y/m/n) 或 string 兩種基礎儲存類型。

類型定義可內建 prompt:


# 等價寫法
bool "Networking support"
# 等同於
bool
prompt "Networking support"

三、選項屬性關鍵字

3.1 輸入提示


prompt "Prompt text" [if ]
  • 每個選項最多一個無條件 prompt
  • 可加 if 條件控制顯示

3.2 預設值


default  [if ]
  • 可定義多個 default,優先使用第一個滿足條件者
  • 可定義在選項外部,被較早定義覆蓋
  • 用戶未修改時生效

3.3 正向依賴


depends on 
# 或
requires 
  • 多個 depends 隱含 && 邏輯
  • 也可用於選單層級,子選項自動繼承父選項依賴

3.4 反向依賴


select  [if ]
  • 強制選擇其他符號 (如選擇 A 自動選擇 B)
  • 僅適用 bool/tristate 類型
  • 多次 select 取最大值 (y > m > n)

3.5 數值範圍


range   [if ]
  • 限制 int/hex 類型輸入範圍

3.6 說明文字


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 時隱藏/強制關閉。

五、選單結構建立

5.1 顯式選單


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

5.2 隱式選單 (依賴推導)

若選項 B depends on 選項 A,且 A 為 bool/tristate 類型,B 自動成為 A 的子選單。需滿足:

  1. A 在依賴列表中
  2. A 為可見選項 (非隱藏)

六、進階技巧與最佳實務

6.1 可見性控制


config ADVANCED_OPTION
    bool "Advanced tuning"
    depends on EXPERT  # 僅專家模式可見

6.2 模組預設值


config BLK_DEV_LOOP
    tristate "Loopback device support"
    default m if BLOCK  # 區塊裝置啟用時預設為模組

6.3 選項別名


config VIRTUALIZATION
    bool "Virtualization support"
    select KVM
    select VHOST_NET

6.4 條件式提示


config CPU_FREQ_GOV_PERFORMANCE
    bool "Performance governor"
    prompt "Performance governor" if CPU_FREQ

七、Kconfig 與 Makefile 協作流程

  1. make menuconfig 讀取 arch/$(ARCH)/Kconfig 遞歸 source 子目錄 Kconfig
  2. 用戶選擇生成 .config (含 CONFIG_XXX=y/m/n)
  3. Makefile 讀取 .config 變數決定編譯目標 (obj-y/obj-m)
  4. 編譯過程中 include/generated/autoconf.h 提供 CONFIG_XXX 宏供 C 代碼使用
Copyright © Windows教程網 All Rights Reserved