1. 程式人生 > >如何向linux核心加入一個驅動模組

如何向linux核心加入一個驅動模組

以最簡單的helloworld模組為例子:
在drivers目錄下面建立一個目錄名為helloworld,在這個資料夾底下有三個檔案helloworld.c,Makefile,Kconfig
原始檔helloworld.c

#include <linux/init.h>
#include <linux/module.h>
static int hello_init(void)
{
        printk("--------------\n");
        printk("hello world\n");
        printk("--------------\n"
); return 0; } static void hello_exit(void) { } module_init(hello_init); module_exit(hello_exit); MODULE_AUTHOR("whoami_I"); MODULE_LICENSE("Dual BSD/GPL");

Makefile

obj-$(CONFIG_HELLO_WORLD) += helloworld.o

Kconfig

config HELLO_WORLD
tristate "HELLO WORLD"

但這個模組怎樣和上一級的Makefile Kconfig發生聯絡呢,那就要修改drivers目錄下的Makefile和Kconfig
drivers/Makefile新增一行

obj-y += helloworld/

obj-y就是編譯的目標,+=後面如果是檔案,則對這個檔案進行編譯,如果後面是資料夾,則進入到資料夾中,包含這個資料夾的Makefile
然後在Kconfig新增一行

source "drivers/helloworld/Kconfig"

這也和Makefile一樣的意思,Kconfig會顯示drivers/helloworld/Kconfig這個Kconfig的配置選項
這樣一個驅動就新增成功了,讓我們看一看效果,在kernel下面執行make menuconfig
這裡寫圖片描述
選擇*後,可以檢視本地的.config檔案,裡面有這樣一項
這裡寫圖片描述
說明配置成功了。
我們注意到menuconfig中有些選項帶有———>符號,這是因為把這些選項配置成了一個目錄的形式,因為需要配置的專案非常多,因此展現在資料夾裡面,我們把helloworld模組也改成這樣,修改Kconfig檔案:

menu "hello world"
config HELLO_WORLD
tristate "HELLO WORLD"
endmenu

多了menu
menuconfig就變成這樣:
這裡寫圖片描述
至此,驅動新增就完成了,把image下載到板子裡面,啟動資訊裡面列印了helloworld的資訊
這裡寫圖片描述