5.2、Hello World驱动程序
1)驱动模块的重要组成部分:
——头文件(必选) #include <linux/modules.h> #include <linux/init.h> 必须要有的
modules.h文件里包含了大量的符号和函数定义;
init.h文件里模块加载和模块的释放函数的宏定义;
——模块参数(可选)
驱动模块加载的时候需要传给驱动模块的参数!~
——模块加载函数(必选)
驱动模块加载的时候运行的函数;
——模块卸载函数(必选)
驱动模块卸载的时候运行的函数;
——模块许可声明(必选)
指的是模块受内核支持的程度
///helloworld驱动模块的代码
#include <linux/module.h> ///必须要有的头文件
#include <linux/init.h> ///必须要有的头文件
int hello_init(void) ///模块加载函数hello_init(必选)
{
printk(KERN_ALERT "hello world\n");
return 0;
}
void hello_exit(void) ///模块卸载函数hello_exit(必选)
{
printk(KERN_ALERT "Goodbye, world\n");
}
module_init(hello_init); ///指定模块加载函数
module_exit(hello_exit); ///指定模块卸载函数
MODULE_LICENSE("Dual BSD/GPL"); ///模块许可声明(必选)
///以上代码就是helloworld的驱动模块代码
Makefile:
ifeq ($(KERNELRELEASE),)
# Assume the source tree is where the running kernel was built
# You should set KERNELDIR in the environment if it's elsewhere
KERNELDIR ?= /linux-2.6.29.4/linux-2.6.29.4
# The current directory is passed to sub-makes as argument
PWD := $(shell pwd)
modules:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
modules_install:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install
clean:
rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions
.PHONY: modules modules_install clean
else
# called from kernel build system: just declare what our modules are
obj-m := hello.o
endif
(3)编译hello_world模块
首先在/dirver/char/Makefile中添加如下内容
在/dirver/char/Kconfig中添加如下内容
然后进行编译make
编译成功得到helloworld.o文件
然后make menuconfig发现新编写helloworld
然后在/dirver/char/目录下创建一个hello目录在当前目录下创建如下三个文件
仿照目录hw_randow下的Kconfig和Makefile文件编写我们hello目录下的文件
make menuconfig得到如下结果
进行make编译
得到如下hello.ko文件编译成功
Linux内核文件,树状,我们的内核里的Makefile文件,也是呈树状结构的!~
=====================================================================================
编译hellowrold模块时必须要满足以下几个条件:
1、内核一定要进行一次make,且make成功!~
2、进行Makefile文件的修改!~