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 2.6.12 內核模組開發入門:編寫、編譯與載入 Hello World 模組

編輯:Linux 教學

實驗環境

  • 運行內核:Linux 2.6.12
  • 交叉編譯器:arm-linux-gcc 3.4.1
  • 目標平台:AT91RM9200 (ARM 架構)

步驟一:編寫模組原始碼 testmodule.c

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>

static int hello_init(void)
{
    printk("Hello! This is the first test module!\n");
    return 0;
}

static void hello_exit(void)
{
    printk("Module exit! Bye Bye!\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");

關鍵點說明:

  • module_init() 與 module_exit() 宏分別指定模組載入與卸載時的入口函數。
  • printk() 是內核空間的輸出函數,訊息會輸出到內核日誌(可用 dmesg 查看)。
  • MODULE_LICENSE("GPL") 聲明授權,避免內核標記為「受污染」。

步驟二:編寫 Makefile

obj-m := testmodule.o
KDIR := /src/linux-2.6.12
PWD := $(shell pwd)

default:
	$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules

注意:

  • $(MAKE) 前必須為一個 Tab 字元,不能用空格。
  • KDIR 指向目標板子運行的內核源碼目錄,且必須與交叉編譯器版本一致,否則模組無法載入。

步驟三:交叉編譯

make CC=/src/3.4.1/bin/arm-linux-gcc

編譯成功後會產生 testmodule.ko(Kernel Object)檔案。

步驟四:在目標板上載入與測試

  1. 透過序列埠或網路將 testmodule.ko 下載到開發板。
  2. 賦予執行權限(雖然 .ko 非執行檔,但習慣上會執行):
    chmod +x testmodule.ko
  3. 載入模組:
    insmod testmodule.ko
    終端應輸出:Hello! This is the first test module!
  4. 移除模組:
    rmmod testmodule.ko
    終端應輸出:Module exit! Bye Bye!

常見問題

  • 版本魔數不符:內核源碼與運行內核版本不一致,需確保 KDIR 指向正確的內核樹。
  • 符號未定義:模組使用了內核未導出的符號,需檢查內核配置(CONFIG_*)。
  • 架構不匹配:編譯器與目標 CPU 架構不符,請確認使用正確的交叉編譯工具鏈。
Copyright © Windows教程網 All Rights Reserved