linux内核模块编译
1 Makefile編寫
ifneq ($(KERNELRELEASE),)
obj-m := mytest.o
mytest-objs := file1.o file2.o file3.o
else
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
?? ??? $(MAKE) -C $(KDIR) M=$(PWD) modules//到linux源碼所在的目錄執(zhí)行主Makefile 并當前路徑傳給主Makefile,告訴主Makefile執(zhí)行完后返回到當前目錄,執(zhí)行Makefile
endif
解釋為:
KERNELRELEASE
是在內(nèi)核源碼的頂層Makefile中定義的一個變量,在第一次讀取執(zhí)行此Makefile時,KERNELRELEASE沒有被定義,
所以make將讀取執(zhí)行else之后的內(nèi)容。如果make的目標是clean,直接執(zhí)行clean操作,然后結(jié)束。當make的目標為all時,-C
$(KDIR) 指明跳轉(zhuǎn)到內(nèi)核源碼目錄下讀取那里的Makefile;M=$(PWD)
表明然后返回到當前目錄繼續(xù)讀入、執(zhí)行當前的Makefile。當從內(nèi)核源碼目錄返回時,KERNELRELEASE已被被定義,kbuild也被啟動去
解析kbuild語法的語句,make將繼續(xù)讀取else之前的內(nèi)容。else之前的內(nèi)容為kbuild語法的語句,
指明模塊源碼中各文件的依賴關(guān)系,以及要生成的目標模塊名。mytest-objs := file1.o file2.o
file3.o表示mytest.o 由file1.o,file2.o與file3.o 連接生成。obj-m :=
mytest.o表示編譯連接后將生成mytest.o模塊。
2 測試
源文件
1 // 2 //hello.c 3 // 4 #include <linux/init.h> 5 #include <linux/kernel.h> 6 #include <linux/module.h> 7 8 static int hello_init(void) { 9 printk(KERN_WARNING "Module init: Hello world!\n"); 10 return 0; 11 } 12 13 static void hello_exit(void) { 14 printk(KERN_WARNING "Module exit: bye-bye\n"); 15 } 16 17 module_init(hello_init); 18 module_exit(hello_exit);Makefile文件
1 ifneq ($(KERNELRELEASE),) 2 obj-m:=hello.o 3 else 4 KDIR := /lib/modules/$(shell uname -r)/build 5 6 all: 7 make -C $(KDIR) M=$(PWD) modules 8 clean: 9 make -C $(KDIR) M=$(PWD) clean 10 endif插入模塊到內(nèi)核
# insmod hello.ko
查看輸出
[root@localhost demo]# dmesg | tail -n 5
<span>[ 2445.017321] virbr0: port 2(vif1.0) entering forwarding state
[ 2445.017439] virbr0: port 2(vif1.0) entering disabled state
[ 2494.639683] hello: module license 'unspecified' taints kernel.
[ 2494.639688] Disabling lock debugging due to kernel taint
[ 2494.639841] Module init: Hello world!
轉(zhuǎn)載于:https://www.cnblogs.com/chengxuyuancc/articles/3001119.html
總結(jié)
以上是生活随笔為你收集整理的linux内核模块编译的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据库——startup,startup
- 下一篇: MPMoviePlayerControl