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 設備驅動開發環境搭建:宿主機與目標機配置指南

編輯:Linux 教學

開發模式對比

模式宿主機目標機適用場景
普通 Linux 驅動開發可與目標機同機x86_64 Linux PC/Server桌面/伺服器驅動、虛擬機內核開發
嵌入式 Linux 驅動開發x86_64 PC (交叉編譯)ARM/MIPS/PowerPC 開發板嵌入式設備、IoT、工控板卡

一、普通 Linux 設備驅動開發環境

1. 宿主機準備

# 安裝開發工具鏈
# Debian/Ubuntu
apt-get install build-essential libncurses5-dev

# RHEL/CentOS
yum groupinstall "Development Tools"
yum install ncurses-devel

# 獲取內核源碼 (版本必須與目標機運行內核一致)
# 方式 A: 官網下載
wget https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.19.200.tar.xz

# 方式 B: 發行版源碼包
apt-get install linux-source-4.19.0   # 解壓至 /usr/src/

# 方式 C: 當前運行內核源碼
# /lib/modules/$(uname -r)/build  (若已安裝 kernel-devel)

2. 內核源碼預處理

cd /usr/src/linux-source-4.19.0
make oldconfig
make prepare
make scripts

3. 編寫第一個驅動

hello.c:

#include 
#include 

static int __init hello_init(void) {
    printk(KERN_ALERT "Hello World linux_driver_module\n");
    return 0;
}
static void __exit hello_exit(void) {
    printk(KERN_ALERT "Goodbye linux_driver_module\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("developer");

Makefile:

obj-m := hello.o
KDIR := /usr/src/linux-source-4.19.0

all:
	$(MAKE) -C $(KDIR) M=$(PWD)

clean:
	rm -f *.mod.c *.mod.o *.ko *.o .*.cmd *.symvers

4. 編譯、加載、測試、卸載

make                    # 生成 hello.ko
insmod hello.ko         # 加載模組
dmesg | tail -5         # 查看內核打印
# 或 cat /proc/kmsg (需 Ctrl+C 退出)
rmmod hello             # 卸載模組

二、嵌入式 Linux 設備驅動開發環境

1. 交叉編譯工具鏈

# ARM 範例
apt-get install gcc-arm-linux-gnueabihf
# 或下載廠商提供的 SDK (含內核源碼、工具鏈、根文件系統)

2. 內核配置與編譯

cd /path/to/kernel-source
make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- menuconfig
# 選擇:Device Drivers → 您的驅動類別 →  模組化編譯

make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- -j$(nproc)
# 生成 zImage、dtb、modules/

3. 部署到開發板

  • NFS 掛載根文件系統:開發板掛載宿主機 /nfsroot,直接 make modules_install INSTALL_MOD_PATH=/nfsroot
  • 或 TFTP 傳輸 .ko 到開發板 /lib/modules/$(uname -r)/kernel/drivers/...

4. 開發板加載測試

# 開發板上
insmod /lib/modules/.../hello.ko
dmesg | tail

關鍵差異總結

  • 普通開發:同架構,直接 make,insmod 即時驗證
  • 嵌入式開發:交叉編譯 ARCH=arm CROSS_COMPILE=...,需部署到目標板驗證
  • 內核源碼版本必須與目標運行內核完全一致 (包括補丁版本)
  • 模組授權 MODULE_LICENSE("GPL") 否則內核標記污染
Copyright © Windows教程網 All Rights Reserved