- 论坛徽章:
- 0
|
初学Linux下的驱动开发。最简单的Hello world示例:
Hello.c:
-------------------------------
#include
#include
#include
MODULE_LICENSE("GPL");
static int hello_init(void)
{
printk("Hello,world!Init
");
return 0;
}
static void hello_exit(void)
{
printk("Good Bye!Exit!
");
}
module_init(hello_init);
module_exit(hello_exit);
Makefile文件:
obj-m += hello.o
default:
make -C /lib/modules/$(shell uname -r)/build/ SUBDIRS=$(PWD) modules
clean:
rm -f .*.cmd *.mod.c *.o *.ko -r .tmp*
执行make,将会编译生成hello.ko。
通过insmod hello.ko加载模块,通过rmmod hello.ko卸载模块。
tail /var/log/syslog,将会看到输出。
上面的示例是基于2.6的内核,对于2.4的核,可以通过如下方式写:
#ifndef __KERNEL__
#define __KERNEL__
#endif
#ifndef MODULE
# define MODULE
#endif
#include
#include
MODULE_LICENSE("GPL");
#ifdef CONFIG_SMP
#define __SMP__
#endif
/* 结束例行公事 */
#include /* printk()在这个文件里 */
static int init_module(){
printk("Hello,World!
");
return 0; /* 如果初始工作失败,就返回非0 */
}
static void cleanup_module(){
printk("Bye!
");
}
关于2.4和2.6的驱动开发的区别,可参考:
http://lwn.net/Articles/driver-porting/
注意:1、对于2.4的驱动模块,似乎需要自己先编译一次内核。2、编译2.4的内核,如果使用gcc4.0会有问题,可降为gcc3.x。3、插入模块:insmod hello.o,删除模块用rmmod hello(如果用rmmod hello.o会出错)。
对于2.4的核,也可以不用编译内核,而直接使用如下Makefile文件:
CC=gccCFLAGS = -D__KERNEL__ -I/usr/src/linux/include -Wall -Wstrict-prototypes -O2 -fomit-frame-pointer -pipe -fno-strength-reduce -mcpu=i686 -DMODULE -DMODVERSIONS -include /usr/src/linux/include/linux/modversions.h
-fno-strict-aliasinghello.o: hello.c gcc -c -I/usr/src/linux/include $(CFLAGS) $clean: rm -f .*.cmd *.mod.c *.o *.ko -r .tmp*
通过研究,我发现,CFLAGES标志的最小集为:
CFLAGS = -D__KERNEL__ -I/usr/src/linux/include -Wall
-DMODULE -DMODVERSIONS
-include /usr/src/linux/include/linux/modversions.h
-fno-strict-aliasing
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/1355/showart_52668.html |
|