一、编写驱动程序
将需要编译进内核的源代码编写好,我举个最简单的Hello World的例子:
hello.c
#include <linux/init.h>
#include <linux/module.h>
static int __init hello_init (void)
{
printk("*****hello init test*****\n");
return 0;
}
static void __exit hello_exit (void)
{
printk("*****hello exit*****\n");
}
module_init (hello_init);
module_exit (hello_exit);
MODULE_LICENSE("GPL");
该文件编译后生成hello.ko文件,在insmod hello.ko的时候会打印 *****hello init test***** ,在rmmod hello的时候打印 *****hello exit*****
我们编写的驱动程序为字符设备驱动,因此我们要将hello.c拷贝至drivers/char目录下。
二、修改Kconfig
Kconfig用来产生make menuconfig的菜单。打开drivers/char目录下的Kconifg,加入如下代码:
config HELLO_WORLD
tristate "my hello world test"
具体Kconfig的编写网上可以找到很多资料。
在Kconfig中加入这项之后,执行make menuconfig ,在Device Drivers -> Character devices 中可以看到多了一项my hello world test:
如果选择将HELLO WORLD编译进内核,即将my hello world test前尖括号中配置为“*”,保存之后看内核代码的根目录下的.config,在字符设备中多了一行CONFIG_HELLO_WORLD=y:
三、修改Makefile
注意修改的是drivers/char下的Makefile,加入obj-$(CONFIG_HELLO_WORLD) += hello.o
重新编译内核,重启之后可以看到内核打印信息中有“ *****hello init test***** ”,如下图:
说明hello_init程序在内核启动的时候就执行了。
而如果将HELLO WORLD配置成模块编译,则内核启动后不会有该条打印信息。
配置成 模块编译 的文件可以使用make modules命令,编译后会生成对应的.ko文件,将.ko文件拷贝至开发板文件系统中用insmod加载才会打印出“ *****hello init test***** ”,并且此时用 lsmod 能看到 一个名为“hello”的模块,
而如果在make menudonfig的时候将模块 编译进内核 则用 lsmod 看不到 hello模块。