ARM Linux 开发板编译字符驱动模块 my_driver.ko
1.下载源码:
源码版本必须和开发板linux内核源码版本号一模一样例如:linux-4.14.111
查看开发板linux版本:uname -r
解压:
sudo tar -zxvf xxxx.tar.gz
2.进入源码/driver目录
driver下新建文件夹:my_driver
在my_driver目录下新建以下三个文件
my_driver.c
#include <linux/module.h>
#include <linux/init.h>
// 当驱动被加载的时候,执行此函数
static int __init my_driver_init(void)
{
printk(KERN_ALERT "welcome, my driver\n");
return 0;
}
// 当驱动被卸载的时候,执行此函数
static void __exit my_driver_exit(void)
{
printk(KERN_ALERT "bye, my driver\n");
}
// 版权声明
MODULE_LICENSE("GPL");
// 以下两个函数属于 Linux 的驱动框架,只要把驱动两个函数地址注册进去即可。
module_init(my_driver_init);
module_exit(my_driver_exit);
注意:
1. 打印信息的级别有好几个,从 DEBUG 到 EMERG,这里使用的是 KERN_ALERT,方便查看打印信息。
2. 命令行使用dmesg | tail 查看printk打印的信息
Kconfig
config MY_DRIVER
tristate "my_driver driver"
help
just a simplest driver.
default y
注意:
1.第一行内容 config MY_DRIVER,在执行配置的时候,将会生成一个变量 MY_DRIVER,而这个变量,将会在编译的时候,被 Makefile 引用。
2.最后一行的 default y ,就表示把 MY_DRIVER的值设置成 y,从而让这个驱动被编译到内核中。
Makefile
obj-$(CONFIG_MY_DRIVER) += my_driver.o
注意:
1.CONFIG_HELLO 可以看做一个变量,在编译的时候,这个变量的值可能是:y, n 或者 m。
2.在刚才的 Kconfig 参数配置中,CONFIG_HELLO 被设置为 y,于是这句话就被翻译成:obj-y += hello,表示把 hello 驱动编译进内核。
3.源码/drivers/Kconfig 文件中配置自己的Kconfig
现在,my_driver驱动中的KConfig配置文件已经准备好了,但是还需要这个配置文件登记到 Linux 内核的整体配置文件中。也就是把它登记在 linux-4.14.111/drivers/Kconfig 文件的末尾:
source "drivers/my_driver/Kconfig"
endmenu // 加在这一句的上面
4.源码/drivers/Makefile文件中添加自己的Makefile部分
#文件最后
obj-$(CONFIG_MY_DRIVER) += my_driver/
5.源码目录下新建 my_make 文件
#!/bin/sh
export CROSS_COMPILE=$HOME/pan/arm_gcc/bin/arm-cortexa9-linux-gnueabihf-
export ARCH=arm
注意:
my_make 文件主要保存一下常用的make 参数,避免每次都要输入一大串
内容为导入编译器前缀和架构:
使用: source ./my_make 即可
6.进入源码目录执行以下命令
source ./my_make
make distclean
清除已经编译过的项目的配置和输出文件,
将目录恢复到源码包中的状态,以便重新编译和构建
make defconfig
作用是生成一个默认的配置文件(.config),
该配置文件包含了内核的顶层默认配置,并确保对所有配置进行了初始化。
当运行这个命令时,内核会使用一组默认的配置参数生成一个新的 .config 文件。
这个 .config 文件可以用于构建和编译内核,也可以在其基础上进行修改。
make menuconfig
在弹出界面找到driver,进入选择自己的my_driver ,设置为[M] ,其中
[M] 为编译成模块
[*] 为编译进内核
由于我只是编译成ko模块,且只要这个模块,遂把其他不用的设置成了[ ]
7.编译
编译成ko模块
make -j8 modules
编译进内核
make -j8
加载驱动
sudo insmod my_drive.ko
查看打印信息
dmesg | tail
卸载驱动
sudo rmmod my_drive