Linux驱动开发入门(一)
在Feodra Linux 14编译驱动非常方便,我们可以使用社区提供好的Package,来进行编译工作。
编译过程
首先在系统中安装kernel相关的package:
yum -y install kernel-devel kernel-headers
安装成功后yum会返回日志类似如下:
Installed: kernel-devel.i686 0:2.6.35.10-74.fc14 Updated: kernel-headers.i686 0:2.6.35.10-74.fc14
Fedora 14会保证内核版本与kernel开发库的代码版本一致,如果需要确认,可以试试看用命令来确认:
uname -a
执行上述命令应该返回结果类似如下:
Linux fedora14 2.6.35.6-45.fc14.i686 #1 SMP Mon Oct 18 23:56:17 UTC 2010 i686 i686 i386 GNU/Linux
与安装的kernel-devel及kernel-headers版本一致即可。
接下来在同一目录下创建两个文件,一个是helloworld.c
#include <linux/module.h> /* Needed by all modules */ #include <linux/kernel.h> /* Needed for KERN_INFO */ #include <linux/init.h> /* Needed for the macros */ static int __init hello_start(void) { printk(KERN_INFO "Loading hello module...\n"); printk(KERN_INFO "Hello world\n"); return 0; } static void __exit hello_end(void) { printk(KERN_INFO "Goodbye Mr.\n"); } module_init(hello_start); module_exit(hello_end);
另一个为Makefile:
# Comment/uncomment the following line to disable/enable debugging #DEBUG = y # Add your debugging flag (or not) to CFLAGS ifeq ($(DEBUG),y) DEBFLAGS = -O -g # "-O" is needed to expand inlines else DEBFLAGS = -O2 endif EXTRA_CFLAGS += $(DEBFLAGS) #-I$(LDDINCDIR) ifneq ($(KERNELRELEASE),) # call from kernel build system obj-m := helloworld.o else KERNELDIR ?= /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) default: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules #LDDINCDIR=$(PWD)/../include modules endif clean: rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions depend .depend dep: $(CC) $(CFLAGS) -M *.c > .depend ifeq (.depend,$(wildcard .depend)) include .depend endif
创建完成后,对代码进行编辑,在上述代码所在目录执行命令如下:
make
编译过程类似如下:
make -C /lib/modules/2.6.35.6-45.fc14.i686/build M=/home/liweinan/projs modules #LDDINCDIR=/home/liweinan/projs/../include modules make[1]: Entering directory `/usr/src/kernels/2.6.35.6-45.fc14.i686' CC [M] /home/liweinan/projs/helloworld.o Building modules, stage 2. MODPOST 1 modules CC /home/liweinan/projs/helloworld.mod.o LD [M] /home/liweinan/projs/helloworld.ko make[1]: Leaving directory `/usr/src/kernels/2.6.35.6-45.fc14.i686'
helloworld.ko就是我们要的module,安装它试试看:
insmod helloworld.ko
如果安装正确则不会有消息返回。看看dmesg里面的日志:
dmesg | tail
应该有下述日志:
[ 1138.690913] helloworld: module license 'unspecified' taints kernel. [ 1138.690915] Disabling lock debugging due to kernel taint [ 1138.691012] Loading hello module... [ 1138.691014] Hello world
说明安装成功。
常见问题
-1 Invalid module format
这个是在安装模块时可能会遇到的问题,一般是由于使用的kernel library与kernel版本不一致造成,在Fedora 14下通过yum安装,应该会由系统保证环境的一致性,但如果你真的遇到了这个问题,那么可能就需要自己来编译Linux Kernel,Fedora针对内核编译也有十分方便的方法,请参考这篇文档 http://fedoraproject.org/wiki/Docs/CustomKernel
关于Linux内核及驱动开发的一些有用资源
文中所用代码来源在这里:http://www.linuxquestions.org/questions/programming-9/trying-to-compile-hello-world-kernel-module-please-help-439353/
http://kernelnewbies.org/ – 面向内核开发新手的网站,不少有用资源
<b