hello world 模块编译

来源:互联网 发布:圆方软件怎么样 编辑:程序博客网 时间:2024/05/21 21:40

772人阅读 评论(0)收藏 举报
makefilemoduleubuntushelllayoutc
[cpp] view plaincopy
  1.    
[cpp] view plaincopy
  1. 1、test.c  
[cpp] view plaincopy
  1. #include <linux/init.h>  
  2. #include <linux/module.h>  
  3.   
  4. static int hello_init(void)  
  5. {  
  6.     printk(KERN_INFO "Hello World enter \n");  
  7. }  
  8.   
  9. static int hello_exit(void)  
  10. {  
  11.     printk(KERN_INFO "Hello World exit\n");  
  12. }  
  13.   
  14. module_init(hello_init);  
  15. module_exit(hello_exit);  


2、Makefile

[html] view plaincopy
  1. obj-m :=test.o  


3、在shell 中键入

 

[cpp] view plaincopy
  1. make -C /usr/src/linux-3.3.1/linux-3.3.1/ M=~/Documents/test/ <span style="color:#ff0000;">modules</span>  

 


 

4、在执行时,出现下面错误:

insmod: error inserting './test.ko': -1 Invalid module format

 

出错信息出现在 /var/log/message 中。

Apr  7 16:27:33 ubuntu kernel: [ 7026.609031] test: disagrees about version of symbol module_layout

 

而模块的相关信息可以通过 modinfo 来看。

 

[cpp] view plaincopy
  1. wangkai@ubuntu:~/Documents/test$ sudo modinfo test.ko  
  2. filename:       test.ko  
  3. license:        Dual BSD/GPL  
  4. srcversion:     A683B0513DFC18A40C79C30  
  5. depends:          
  6. vermagic:       3.3.1-20120406 SMP mod_unload modversions 68  

 

内核无法加载模块的原因是因为记载版本号的字符串和当前正在运行的内核模块的不一样,这个版本印戳作为一个静态的字符串存在于内核模块中,叫vermagic
真正的原因是由于当前的内核源码和系统版本不相匹配。 当前正在运行的系统的 为ubuntu 10.10的内核。而源码则为 3.3.1的源码。故出错。

 

5、解决问题的方法 是

[cpp] view plaincopy
  1. $ make -C /usr/src/linux-headers-2.6.35-22-generic/  M=~/Documents/test/ modules  


二、通过写Makefile的方法,使得模块的勾走更加简单。

1、最简单的方法是,把上面的命令写进Makefile中即可。

[cpp] view plaincopy
  1. obj-m :=test.o  
  2.   
  3. kernel_modules:  
  4.      make -C /usr/src/linux-headers-2.6.35-22-generic/  M=/home/wangkai/Documents/test/ modules  
  5.   
  6. clean:  
  7.      make -C /usr/src/linux-headers-2.6.35-22-generic/  M=/home/wangkai/Documents/test/ clean  

 

2、但是这种方式,不够通用,可以写得更加通用些。

[cpp] view plaincopy
  1. KVER = $(shell uname -r)  
  2.   
  3. obj-m :=test.o  
  4.   
  5. kernel_modules:  
  6.      make -C /lib/modules/$(KVER)/build  M=$(PWD) modules  
  7.   
  8. clean:  
  9.      make -C /lib/modules/$(KVER)/build  M=$(PWD) clean  

 

编译时,只需

[csharp] view plaincopy
  1. make  


重新编译时,只需

[cpp] view plaincopy
  1. make clean  




 

0 0