在Ubuntu下开发驱动程序


首先,建立一个目录作为自己的工作目录,比如我的是~/kernel/mymodule。然后,新建一个hello.c文件,代码如下:
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSP/GPL");

static int hello_init(void)
{
printk(KERN_ALERT "Hello,world.\n");
return 0;
}


static int hello_exit(void)
{
printk(KERN_ALERT "Goodbye, cruel world.\n");
return 0;
}


module_init(hello_init);
module_exit(hello_exit);
再建立一个Makefile文件,注意文件名字是“Makefile”,不能是“makefile”或其它名字。文件内容如下:
# If KERNELREALEASE is defined, we've been invoked from the
# kernel build system and can use its language
ifneq ($(KERNELRELEASE),)
obj-m := hello.o


# Otherwise we were called directly from the command
# line; invoke the kernel build system
else
KERNELDIR ?= /usr/src/linux-headers-3.2.0-23-generic-pae/
PWD := $(shell pwd)


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

endif
其中,“linux-headers-3.2.0-23-generic-pae”是我机器上使用的内核版本。可以使用“uname -a”命令查看。
然后,直接在命令行敲入make就可以编译了。
编译成功后,使用sudo insmod ./hello.ko安装,lsmod查看已经安装的模块,rmmod hello卸载模块。
很多书上说要先下载源码才能编译模块,但我的测试是不用。当然,下载源码编译学习对驱动开发来说也是很重要的。

相关内容