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、Makefile 與選單配置實戰

編輯:Linux 教學

將自訂驅動程式整合進 Linux 核心原始碼樹,需完成三大步驟:原始碼放置、Kconfig 選單配置、Makefile 編譯規則。本文以字元設備驅動 usbtmc 為例,詳細演示從複製原始碼到 make menuconfig 選單出現選項的完整流程。

核心原始碼樹驅動目錄架構

drivers/
├── char/        # 字元設備
├── block/       # 區塊設備
├── usb/         # USB 設備
└── ...

原則:依設備類型歸類。USB 設備同時也是字元設備,可放 drivers/usb/ 或 drivers/char/。單一檔案可直接置於分類目錄;多檔案建議建立子目錄(如 drivers/char/usbtmc/)。

三大核心步驟

步驟 1:放置驅動原始碼

cp -r usbtmc/ /usr/src/linux-2.6.32/drivers/char/

步驟 2:修改上層目錄 Kconfig 與 Makefile

編輯 drivers/char/Kconfig:

source "drivers/char/usbtmc/Kconfig"

編輯 drivers/char/Makefile:

obj-$(CONFIG_USBTMC) += usbtmc/

說明: CONFIG_USBTMC 為下層 Kconfig 定義的配置選項,若選 y/m 則進入子目錄編譯。

步驟 3:在驅動目錄建立 Kconfig 與 Makefile

drivers/char/usbtmc/Kconfig:

menu "USBTMC"
comment "USBTMC Driver"
config USBTMC
    tristate "USBTMC"
    default n
    help
      If you say Y here, support for the usbtmc with computer interface
      will be compiled into the kernel and accessible via device node.
      You can also say M here and the driver will be built as a module
      named usbtmc.ko. If unsure, say N.
endmenu

drivers/char/usbtmc/Makefile:

# 單一來源檔
obj-$(CONFIG_USBTMC) += usbtmc.o

# 多來源檔(範例)
# obj-$(CONFIG_USBTMC) += usbtmc.o
# usbtmc-objs := usbtmc-main.o usbtmc-usb1.o

驗證與編譯

cd /usr/src/linux-2.6.32
make menuconfig
# Device Drivers → Character devices → USBTMC → 選 Y/M
make -j$(nproc)
# 模組產出:drivers/char/usbtmc/usbtmc.ko

移除驅動

  1. 刪除 drivers/char/usbtmc/ 目錄
  2. 從 drivers/char/Kconfig 移除 source "drivers/char/usbtmc/Kconfig"
  3. 從 drivers/char/Makefile 移除 obj-$(CONFIG_USBTMC) += usbtmc/

關鍵概念總結

檔案角色關鍵語法
Kconfig定義選單選項、相依性、說明文字config, tristate, default, help, source
Makefile定義編譯規則、物件檔、子目錄遞迴obj-y, obj-m, obj-$(CONFIG_XXX), xxx-objs

提示: 現代核心(5.x+)建議優先撰寫獨立模組(out-of-tree),使用 M=$(pwd) 編譯,避免修改主線原始碼樹,便於維護與 DKMS 自動重建。

掌握 Kconfig/Makefile 機制,即可將任何驅動無縫整合進核心建置體系,實現模組化開發與配置管理。

Copyright © Windows教程網 All Rights Reserved