Linux驱动 编译一个hello模块

By | 2019-09-23

记录一点linux驱动学习笔记,方便以后查阅

Linux驱动 编译一个hello模块
Linux驱动 实现一个字符设备驱动
Liunx驱动 实现一个misc设备驱动

编写hello world模块代码

在内核源码driver目录创一个hello_driver的目录,并分别创建hello_kernel.c、Kconfig、Makefile三个文件

hello_kernel.c代码如下:

#include<linux/kernel.h>
#include<linux/module.h>

static int __init hello_init(void)
{
    printk("Hello, kernel instaled!\n");
    return 0;
}

static void __exit hello_cleanup(void)
{
    printk("Good bye, removed!\n");
}

module_init(hello_init);
module_exit(hello_cleanup);
MODULE_LICENSE("GPL");

这里使用内核根目录下的Makefile进行编译。
Makefile代码如下:
obj-$(CONFIG_HELLO_KERNEL) += hello_kernel.o

Kconfig代码如下:

menu "hello_driver"
    config HELLO_KERNEL
        tristate "hello_kernel"
        default n
    help
        if you select, you can use it

endmenu
  • menu:配置选项的菜单
  • config:要配置的参数
  • tristate:表示有三种状态可配置,M以模块编译,×编译成.o
  • default:默认配置,有y,n,还可以写模块(y if xxmod)
  • help:提示信息,可以自由添加
  • Kconfig配置有很多,可以copy其他配置多尝试,然后make menuconfig看效果

修改内核配置文件

1.打开内核源码drivers目录的Kconfig,在endmenu上面添加source "drivers/hello_driver/Kconfig"

2. 在内核源码根目录执行make menuconfig进入Device Drivers,移动到最下面可以看到添加的选项

3. 按回车进入,空格键进行配置

4. 编译前还需要修改内核驱动目录Makefile文件
因为是使用内核源码进行编译,所以需要将新增的hello_driver目录添加到内核源码drivers的Makefile里

5. 编译内核代码
内核跟目录下执行make -j4,生成驱动模块

root@linux:/zdisk/linux-5.0.6/drivers/hello_driver# ls
hello_kernel.c   hello_kernel.mod.c  hello_kernel.o  Makefile
hello_kernel.ko  hello_kernel.mod.o  Kconfig         modules.order

验证结果

为了方便,这里手动加载/卸载驱动文件,insmod hello_kernel.ko/rmmod hello_kernel.ko
输入dmesg,查看日志,有打印hello_driver.c中的字符串

发表评论

邮箱地址不会被公开。 必填项已用*标注