Linux 驱动加载到内核中编译<2>
前面只是简单的一个文件,如果一个驱动是多个文件,还放在char目录下,将来维护不是很方便,这样做,可以直接在drivers目录下新建自己的一个目录用来放自己开发的驱动.
步骤如下:
<1> : 首先编写出驱动程序:
main.c
#include<linux/kernel.h> #include<linux/fs.h> #include<linux/module.h> #include<linux/init.h> #include<linux/miscdevice.h> #include<asm/uaccess.h> #include "product.h" extern int add(int x1,int x2); static int __init main_init(void){ printk("hello driver init!\n"); int x1=20; int x2=68; printk("%d + %d = %d\n",x1,x2,add(x1,x2)); printk("product name : %s\n",get_product_name()); return 0; } static void __exit main_exit(void){ printk("hello driver exit!\n"); } module_init(main_init); module_exit(main_exit); MODULE_AUTHOR("zhibao.liu"); MODULE_DESCRIPTION("hello driver information !"); MODULE_ALIAS("hello driver alias !"); MODULE_LICENSE("GPL");
fun.c
int add(int x1,int x2){ return x1+x2; }
product.c
#include"product.h" char* get_product_name(void){ return "product name : hello driver"; }
product.h
extern char* get_product_name(void);
Makefile:
obj-m := hellodriver.o
hellodriver-y := fun.o product.o main.o
模块名:hellodriver
build.sh
#!/bin/bash make -C /usr/src/linux-headers-3.8.0-29-generic M=/root/workspace/drivers/hellodriver
build_t.sh
#!/bin/bash insmod hellodriver.ko dmesg | grep hellodriver echo "-----------------------------------------------" # modinfo hellodriver.ko lsmod | grep hellodriver rmmod hellodriver echo "-----------------------------------------------" modinfo hellodriver.ko
<2> : 上面文件准备完成后,编译运行试一下,不出错误就可以了.
<3> : 在要编译的内核drivers目录下新建一个文件夹hellodriver
将上面的*.c,*.h文件拷贝进去,然后冲char文件夹下拷贝Kconfig和Makefile进去,这样就不要自己单独新建了,
删除Kconfig和Makefile里面不要的,添加自己的.
如下:
Kconfig:
# # Hello device configuration # menu "Hello devices" config HELLO_DRIVER bool "hello driver test" default y endmenu
Makefile:
obj-$(CONFIG_HELLO_DRIVER) += hellodriver.o
hellodriver-y := fun.o product.o main.o
<4> : 上面的Kconfig只能代表hellodriver目录下文件关系,但是hellodriver和drivers文件关系没有建立,即要修改drivers下Kconfig的配置,让它能够找到hellodriver文件目录.
source "drivers/char/Kconfig" source "drivers/hellodriver/Kconfig"
我将其插入在char后面,source相当于include作用,导入(引入)的作用.
同时还需要drivers目录下的Makefile配置:
obj-y += char/ obj-y += hellodriver/
我同样插入到char目录后面.
<5> : 这样驱动程序编写完成,文件关系建立,就可以make menuconfig:

<6> : 选择并且保存,就可以make bzImage后就可以得到新的内核,当然你可以只编译模块,make modules.

浙公网安备 33010602011771号