歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 在Ubuntu下開發驅動程序

在Ubuntu下開發驅動程序

日期:2017/3/1 10:23:47   编辑:Linux編程

首先,建立一個目錄作為自己的工作目錄,比如我的是~/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卸載模塊。
很多書上說要先下載源碼才能編譯模塊,但我的測試是不用。當然,下載源碼編譯學習對驅動開發來說也是很重要的。

Copyright © Linux教程網 All Rights Reserved