Chinaunix首页 | 论坛 | 博客
  • 博客访问: 724078
  • 博文数量: 251
  • 博客积分: 10367
  • 博客等级: 上将
  • 技术积分: 2750
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-10 14:43
文章分类

全部博文(251)

文章存档

2009年(2)

2008年(86)

2007年(163)

分类: LINUX

2007-07-14 01:15:35


#include <linux/init.h>  //注意如果没有包含这个头文件,则编译时产生警告,//insmod hello.ko后也没有输出。
#include <linux/module.h>
 
MODULE_LICENSE("Dual BSD/GPL");
 
static int hello_init(void)
{
        printk(KERN_ALERT"hello,world\n");
        return 0;
 
}
 
 
static void hello_exit(void)
{
 
        printk(KERN_ALERT"Goodbye,cruel world\n");
 
}
 
module_init(hello_init);
module_exit(hello_exit);


说明: 与2.4 内核驱动的不同之处在于:
 1、 使用新的入口

必须包含

module_init(your_init_func);

module_exit(your_exit_func);

老版本:
        int init_module(void);

       void cleanup_module(voi);

2.4中两种都可以用,对如后面的入口函数不必要显示包含任何头文件。

2、 GPL

MODULE_LICENSE("Dual BSD/GPL");

老版本:MODULE_LICENSE("GPL");

Makefile 的编写

(NOTE:ifneq后面一定要加一个空格,要不然不能编译成功!)

 


ifneq ($(KERNELRELEASE),)
obj-m := hello.o
 
else
 
        KERNELDIR ?= /lib/modules/$(shell uname -r)/build
        PWD :=$(shell pwd)
default:
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
 
endif


make 之后生成了如下文件:
[root@hujunlinux drivers]# ls
hello.c  hello.ko  hello.mod.c  hello.mod.o  hello.o  makefile






这里说一下
 在 结构体的初试化时,2.6的kernel ,gcc开始采用ANSI C的struct结构体的初始化形式:

static struct some_structure = {

.field1 = value,

.field2 = value,

...

};

老版本:非标准的初试化形式

static struct some_structure = {

field1: value,

field2: value,

...

};

试验了一下:
                                               
                                                                              
                                                                              



#include <stdio.h>
                                                                              
int main()
{
    typedef struct my_struct
        {
                int a;
                int b;
        } mystruct ;
                                                                              
        mystruct A={
                    .a=2,
                    .b=3
                  };
   printf("A.a=%d,A.b=%d\n",A.a,A.b);
                                                                              
   return 0;
 } 

//模块参数 练习



#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
 
 
MODULE_LICENSE("Dual BSD/GPL");
 
static char *whom ="world";
static int howmany =1;
 
module_param(howmany,int,S_IRUGO);
module_param(whom,charp,S_IRUGO);
 
 
static int hello_init(void)
{
        int i=howmany;
        for(;i>0;i--)
        {
                printk(KERN_ALERT"hello,%s\n",whom);
        }
        return 0;
 
}
 
 
static void hello_exit(void)
{
 
        printk(KERN_ALERT"Goodbye,cruel world\n");
 
}
 
module_init(hello_init);
module_exit(hello_exit);


转自:http://blog.chinaunix.net/u/24474/showart_217342.html
阅读(3431) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2009-03-03 11:46:37

非常好!解决了我的难题,非常感谢!