3 Linux内核中加载自己的驱动模块
3.1 构建驱动模块所需的3个文件——.c文件、hello_module.c、Makefile、Kconfig
1、使用命令进入linux-5.18.7目录
cd linux-5.18.7/drivers
2、创建自己的模块文件夹
mkdir hello
3、在hello下要创建3个文件分别是hello_module.c、Makefile、Kconfig,第一个文件是hello_module.c
cd hello
4、编写hello_module.c
vim hello_module.c
以下为hello_dodule.c中的要编写的内容
#include <linux/module.h> //所有模块都需要的头文件
#include <linux/init.h> // init&exit相关宏
#include <linux/kernel.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David");
MODULE_DESCRIPTION("My first module");
static int __init hello_init(void)
{
printk(KERN_WARNING "Hello world!\n");
return 0;
}
static void __exit hello_exit(void)
{
printk(KERN_WARNING "Exit!\n");
}
module_init(hello_init);
module_exit(hello_exit);
5、创建Makefile文件
vim Makefile
将Makefile文件中加入以下代码
obj-$(CONFIG_HELLO) += hello.o
6、创建Kconfig文件
vim Kconfig
将Konfig文件中加入以下代码
menu "HELLO TEST Driver "
comment "HELLO TEST Driver Config"
config HELLO
tristate "hello module test"
default m
help
This is the hello test driver --by baoli.
endmenu
3.2 修改linux-5.18.7/drivers目录中的Kconfig和Makefile文件
1、回到linux-5.18.7/drivers/目录
2、编辑Makefile,在后面添加一行:
obj-$(CONFIG_HELLO) += hello_module/
3、编辑Kconfig,在后面添加一行:
source "drivers/hello/Kconfig"
3.3 make menuconfig 配置Linux内核
1、进入linux-5.18.7目录
2、执行以下命令
make menuconfig
3、可以看到最后是我们添加的hello_module模块了
4、进入 HELLO TEST Driver选项,如下图所示
以下是<>内表示的含义:
<Y>:编译进内核
<N>:不编译
<M>:编译成模块
5、因此,我们选M就是我们选择编译成模块<M>编译内核过程中输出:
LD drivers/hello/built-in.o
CC [M] drivers/hello/hello.o
CC drivers/hello/hello.mod.o
LD [M] drivers/hello/hello.ko
② 选择编译进内核<y>编译内核输出:
CC drivers/hello/hello.o
LD drivers/hello/built-in.o
编译完成后,drivers/hello/下会出现2个文件(hello.o、hello.ko),并且/linux-5.18.7/output/lib/modules/5.18.7/下也会有hello.ko。
编译过程中总会抛出很多异常,PC系统不同异常也不同,这时需要耐心去解决,欢迎你在留言区提问,看到后我会及时回复!谢谢!