hello内核模块编译的全过程

来源:互联网 发布:新人淘宝刷単教程 编辑:程序博客网 时间:2024/04/30 04:26

      在/home目录下建两个文件hello.c和Makefile

      hello.c

.....................................................

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>

MODULE_LICENSE("GPL");

static int hello_init(void)
{
printk(KERN_EMERG "hello module init\n");
return 0;
}

static void hello_exit(void)
{

printk(KERN_EMERG "hello module exit\n");
}

module_init(hello_init);
module_exit(hello_exit);

--------------

Makefile
----------
ifneq ($(KERNELRELEASE),)
obj-m := hello.o
else
KERNELDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)

default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif

clean:
rm -f *.ko *.mod.c *.mod.o *.o

..................

编译模块

#make

清除

#make clean

-----------

有以下几点要注意:
1,hello.c文件中调用的头文件
init.h中的module_init(),module_exit()
kernel.h中的printk(),KERN_ALERT
module.h中的MODULE_LICENSE()

2,Makefile文件中的核心是
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
1),-C $(KERNELDIR)
表示在$(KERNELDIR)目录下执行make命令。
2),M=$(PWD)
表示包含$(PWD)下的Makefile文件。
3),modules
表示模块编译。
4), 用到了ifneq...else...endif语句
由于开始还没定义KERNELRELEASE,所以只能执行else分支。
而在执行
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
后,会在内核的Makefile中定义KERNELRELEASE,当进入本Makefile时,
则只会执行ifneq的第一个分支,即
obj-m := hello.o
这一句话是非常重要的。事实上,这个Makefile做的本份工作就是它。
我们也可以用命令行的方式来编译:

在Makefile中的内容写为:
obj-m := hello.o
然后在终端敲入:
#make -C /lib/modules/2.6.10/build M=/home/tmp modules