Chinaunix首页 | 论坛 | 博客
  • 博客访问: 347214
  • 博文数量: 37
  • 博客积分: 1331
  • 博客等级: 少尉
  • 技术积分: 760
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-11 14:33
文章分类

全部博文(37)

文章存档

2015年(1)

2014年(4)

2013年(1)

2012年(2)

2011年(25)

2010年(4)

分类: LINUX

2012-06-12 16:24:55

内核版本:2.6.10

在/home/tmp/下建立两个文件hello.c,Makefile

hello.c
------------
#include
#include
#include

MODULE_LICENSE("GPL");

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

static void hello_exit(void)
{
printk(KERN_ALERT "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

-----------

为了能够在终端显示信息,要修改
/lib/modules/2.6.10/build/include/linux/kernel.h
文件的KERN_ALERT宏。
#define KERN_ALERT "<1>"
修改为
#define KERN_ALERT "<0>"

------------
安装模块

#insmod hello.ko

终端显示
hello module init

查看已安装的模块
#lsmod

卸载模块

#rmmod hello

终端显示
hello module exit

-----------
有以下几点要注意:
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


阅读(1130) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~