Linux 最簡單核心模組 Hello World 樣本,linuxhello
註:如果想要按照本篇實踐,需要有能啟動並執行arm開發板和對應版本的核心(如果想在Linux主機上編譯運行,請參考文末附1)
1. 在相應版本核心的drivers目錄下建立如下檔案:
module file tree
其中檔案代碼如下:
/* hello.c */
#include <linux/init.h>#include <linux/module.h>static int hello_init(void){ printk(KERN_INFO "[init] Can you feel me?\n"); return 0;}static void hello_exit(void){ printk(KERN_INFO "[exit] Yes.\n");}module_init(hello_init);module_exit(hello_exit);MODULE_AUTHOR("Alan Wang <alan@wrcode.com>");MODULE_LICENSE("GPL");MODULE_DESCRIPTION("A simple Hello World Module");MODULE_ALIAS("A simple module");
/* Kconfig */
# drivers/alan_test/Kconfigmenu "ALAN_TEST Driver "comment "ALAN_TEST Driver comment"config ALAN_TEST bool "ALAN_TEST support"config HELLO tristate "hello module test" depends on ALAN_TESTendmenu
/* Makefile */
# drivers/alan_test/Makefile# makefile for the ALAN_TESTobj-$(CONFIG_HELLO) += hello.o
2. 修改上一級目錄的 Kconfig Makefie:
drivers 下的 Kconfig 末尾 endmenu 前添加一行
source "drivers/alan_test/Kconfig"endmenu
drivers 下的 Makefile 末尾加一行
obj-$(CONFIG_ALAN_TEST) += alan_test/
3. make menuconfig 添加剛寫好的模組到核心:
依次是:Device Drivers —->
ALAN_TEST Driver —->
*** ALAN_TEST Driver comment ***
[*] ALAN_TEST support
< M > hello module test
退出儲存 menuconfig
4. 編譯核心:
使用 make 編譯
產生的 zImage (arch/arm/boot/zImage) 燒寫到開發板對應位置。
產生的 hello.ko(drivers/alan_test/hello.ko) 複製到開發板Linux系統的一個目錄下。
5. 插入核心模組:
insmod
6. 使用 modinfo 查看模組資訊:
modinfo
附1:編譯模組在PC上運行
把 hello.c 和 Makefile 放在同一目錄
/* Makefile */
KERNEL_VER = $(shell uname -r)# kernel modulesobj-m += hello.o# specify flags for the module compilationEXTRA_CFLAGS = -g -O0build: kernel_moduleskernel_modules: make -C /lib/modules/$(KERNEL_VER)/build M=$(CURDIR) modulesclean: make -C /lib/modules/$(KERNEL_VER)/build M=$(CURDIR) clean
編譯運行步驟如:
hello模組在PC上編譯運行