一、编写驱动程序

  将需要编译进内核的源代码编写好,我举个最简单的Hello World的例子:

  hello.c

 1 #include <linux/init.h>
 2 #include <linux/module.h>
 3 
 4 static int __init hello_init (void)
 5 {
 6     printk("*****hello init test*****\n");
 7     
 8     return 0;
 9 }
10 
11 static void __exit hello_exit (void)
12 {
13     printk("*****hello exit*****\n");
14 }
15 
16 module_init (hello_init);
17 module_exit (hello_exit);
18 
19 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模块。