1、目录组织结构如下,本文主要讨论几个问题:不同模块之间如何相互调用;如何使用多个源文件生成一个ko文件;采用多个子目录
2、模块通过EXPORT_SYMBOL导出函数,供其他模块使用.hello_.c
#include <linux/init.h>
#include <linux/module.h>
#include "common.h"
static int hello_init(void){
printk(KERN_ALERT "Hello ,modules world!\n");
lib1();
return 0;
}
static void hello_exit(void){
printk(KERN_ALERT "Goodby,cruel world\n");
}
void func(void){
printk("This is func\n");
}
MODULE_LICENSE("Dual BSD/GPL");
module_init(hello_init);
module_exit(hello_exit);
EXPORT_SYMBOL(func);
然后在hello2.c中就可以直接使用了:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
//This function is define in module hello
void func(void);
int __init hello_init(void){
printk("hello 2 !\n");
func();
return 0;
}
void __exit hello_exit(void){
printk("hello 2 exit\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("Dual BSD/GPL");
3、使用多个源文件生成一个ko文件,详细参照Kbuild文档:
obj-m := hello.o
#This will link hello_.o and common.o to hello.ko
hello-objs += hello_.o common.o
4、项目主(根)目录下的Makefile改为:
obj-m += hello/
obj-m += hello2/
obj-m += hello3/
make时将自动执行hello/目录下的Makefile文件
5、尝试在多处EXPORT_SYMBOL同一函数:在hello3.c中又定义一个名为func的函数,并导出:
echo "Kernel version: `uname -r`"
Kernel version: 3.13.0-24-generic
echo "kernel sources: "/lib/modules/`uname -r`/build""
kernel sources: /lib/modules/3.13.0-24-generic/build
make -C "/lib/modules/`uname -r`/build" SUBDIRS=`pwd` modules
make[1]: Entering directory `/usr/src/linux-headers-3.13.0-24-generic'
CC [M] /home/zhijian/work/fs/module_test/hello/hello_.o
CC [M] /home/zhijian/work/fs/module_test/hello/common.o
LD [M] /home/zhijian/work/fs/module_test/hello/hello.o
CC [M] /home/zhijian/work/fs/module_test/hello2/hello2.o
CC [M] /home/zhijian/work/fs/module_test/hello3/hello3.o
Building modules, stage 2.
MODPOST 3 modules
WARNING: /home/zhijian/work/fs/module_test/hello3/hello3: 'func' exported twice. Previous export was in /home/zhijian/work/fs/module_test/hello/hello.ko
CC /home/zhijian/work/fs/module_test/hello/hello.mod.o
LD [M] /home/zhijian/work/fs/module_test/hello/hello.ko
CC /home/zhijian/work/fs/module_test/hello2/hello2.mod.o
LD [M] /home/zhijian/work/fs/module_test/hello2/hello2.ko
CC /home/zhijian/work/fs/module_test/hello3/hello3.mod.o
LD [M] /home/zhijian/work/fs/module_test/hello3/hello3.ko
make[1]: Leaving directory `/usr/src/linux-headers-3.13.0-24-generic'
得到警告 'func'exported twice。