免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1101 | 回复: 0
打印 上一主题 下一主题

驱动开发示例 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-10-20 11:36 |只看该作者 |倒序浏览
初学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
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP