陸陸續續也寫了幾個Linux核心模組了,但每次都是把代碼寫在一個源檔案中,上次嘗試了寫在兩個.c檔案中,結果沒有編譯通過。
無奈之下,將其中一個.c檔案重新命名成.h檔案,再include當另一個當中。但是,在.h檔案中寫函數的實現總感覺怪怪的。
今天查看了以下Kbuild的文檔,有如下描述:
If a kernel module is built from several source files, you specify
that you want to build a module in the same way as above.
Kbuild needs to know which the parts that you want to build your
module from, so you have to tell it by setting an
$(<module_name>-objs) variable.
Example:
#drivers/isdn/i4l/Makefile
obj-$(CONFIG_ISDN) += isdn.o
isdn-objs := isdn_net_lib.o isdn_v110.o isdn_common.o
In this example, the module name will be isdn.o. Kbuild will
compile the objects listed in $(isdn-objs) and then run
"$(LD) -r" on the list of these files to generate isdn.o.
整理自己的源檔案成兩個.c檔案(simpLB.c和sahu_lb_tools.c)、一個.h檔案(sahu_lb.h)和Makefile檔案。兩個.c檔案都包含了sahu_lb.h
按照Kbuild的文檔所述,把Makefile改成如下內容:
obj-m +=simpLB.o
simpLB-objs:=sahu_lb_tools.o
all:
make -C /lib/modules/`uname -r`/build M=`pwd`
clean:
make -C /lib/modules/`uname -r`/build M=`pwd` clean
install:
/sbin/insmod simpLB.ko
remove:
/sbin/rmmod simpLB
編譯沒有問題,但是安裝後模組的功能沒有實現,就連我在init_module()中列印的提示資訊都沒有。lsmod卻有simpLB。
只好再上網查了查,發現如下文章:
http://www.linuxquestions.org/questions/programming-9/linking-multiple-files-kernel-module-programming-701735/
按照文章的的建議,我把Makefile修改成如下內容:
obj-m +=sahuLB.o
sahuLB-objs:=simpLB.o sahu_lb_tools.o
all:
make -C /lib/modules/`uname -r`/build M=`pwd`
clean:
make -C /lib/modules/`uname -r`/build M=`pwd` clean
install:
/sbin/insmod sahuLB.ko
remove:
/sbin/rmmod sahuLB
問題解決!