如何向linux内核加入一个驱动模块

以最简单的helloworld模块为例子:
在drivers目录下面建立一个目录名为helloworld,在这个文件夹底下有三个文件helloworld.c,Makefile,Kconfig
源文件helloworld.c

#include <linux/init.h>
#include <linux/module.h>
static int hello_init(void)
{
        printk("--------------\n");
        printk("hello world\n");
        printk("--------------\n");
        return 0;
}
static void hello_exit(void)
{
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_AUTHOR("whoami_I");
MODULE_LICENSE("Dual BSD/GPL");

Makefile

obj-$(CONFIG_HELLO_WORLD) += helloworld.o

Kconfig

config HELLO_WORLD
tristate "HELLO WORLD"

但这个模块怎样和上一级的Makefile Kconfig发生联系呢,那就要修改drivers目录下的Makefile和Kconfig
drivers/Makefile添加一行

obj-y += helloworld/

obj-y就是编译的目标,+=后面如果是文件,则对这个文件进行编译,如果后面是文件夹,则进入到文件夹中,包含这个文件夹的Makefile
然后在Kconfig添加一行

source "drivers/helloworld/Kconfig"

这也和Makefile一样的意思,Kconfig会显示drivers/helloworld/Kconfig这个Kconfig的配置选项
这样一个驱动就添加成功了,让我们看一看效果,在kernel下面运行make menuconfig
这里写图片描述
选择*后,可以查看本地的.config文件,里面有这样一项
这里写图片描述
说明配置成功了。
我们注意到menuconfig中有些选项带有———>符号,这是因为把这些选项配置成了一个目录的形式,因为需要配置的项目非常多,因此展现在文件夹里面,我们把helloworld模块也改成这样,修改Kconfig文件:

menu "hello world"
config HELLO_WORLD
tristate "HELLO WORLD"
endmenu

多了menu
menuconfig就变成这样:
这里写图片描述
至此,驱动添加就完成了,把image下载到板子里面,启动信息里面打印了helloworld的信息
这里写图片描述

猜你喜欢

转载自blog.csdn.net/whoami_I/article/details/82156887
今日推荐