经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » Linux/Shell » 查看文章
linux内核模块编译-通过Makefile重命名.ko文件名和模块名
来源:cnblogs  作者:先之  时间:2021/5/6 17:49:01  对本文有异议

模块的源文件为hello.c,源码如下:

  1. #include <linux/module.h>
  2. #include <linux/kernel.h>
  3. #include <linux/fs.h>
  4. #include <linux/init.h>
  5. #include <linux/delay.h>
  6. #define HELLO_MAJOR 231
  7. #define DEVICE_NAME "HelloModule"
  8. static int hello_open(struct inode *inode, struct file *file)
  9. {
  10. printk(KERN_EMERG "hello open.\n");
  11. return 0;
  12. }
  13. static ssize_t hello_write(struct file *file, const char __user *buf,
  14. size_t count, loff_t *ppos)
  15. {
  16. printk(KERN_EMERG "hello write.\n");
  17. return 0;
  18. }
  19. static struct file_operations hello_flops = {
  20. .owner = THIS_MODULE,
  21. .open = hello_open,
  22. .write = hello_write,
  23. };
  24. static int __init hello_init(void)
  25. {
  26. int ret;
  27. ret = register_chrdev(HELLO_MAJOR, DEVICE_NAME, &hello_flops);
  28. if (ret < 0) {
  29. printk(KERN_EMERG DEVICE_NAME
  30. " can't register major number.\n");
  31. return ret;
  32. }
  33. printk(KERN_EMERG DEVICE_NAME " initialized.\n");
  34. return 0;
  35. }
  36. static void __exit hello_exit(void)
  37. {
  38. unregister_chrdev(HELLO_MAJOR, DEVICE_NAME);
  39. printk(KERN_EMERG DEVICE_NAME " removed.\n");
  40. }
  41. module_init(hello_init);
  42. module_exit(hello_exit);
  43. MODULE_LICENSE("GPL");

使用该文件编译内核模块。
正常情况下,Makefile文件内容如下:

  1. ifneq ($(KERNELRELEASE),)
  2. obj-m:=hello.o
  3. $(info "2nd")
  4. else
  5. KDIR := /lib/modules/$(shell uname -r)/build
  6. PWD:=$(shell pwd)
  7. all:
  8. $(info "1st")
  9. make -C $(KDIR) M=$(PWD) modules
  10. clean:
  11. rm -f *.ko *.o *.mod .*.cmd *.symvers *.mod.c *.mod.o *.order .hello*
  12. endif

执行make命令,生成hello.ko文件。
执行sudo insmod hello.ko命令,安装该模块。
执行lsmod命令,查看安装的模块。就会看到第一行的就是hello模块。

但是,如果想自定义模块名称为xmodule,而不是默认的hello,如何实现呢?方法如下:
在Makefile中重命名obj-m并将obj-m的依赖关系设置为原始模块(hello)
修改后的Makefile文件内容如下:

  1. ifneq ($(KERNELRELEASE),)
  2. obj-m:=xmodule.o
  3. xmodule-objs := hello.o
  4. $(info "2nd")
  5. else
  6. KDIR := /lib/modules/$(shell uname -r)/build
  7. PWD:=$(shell pwd)
  8. all:
  9. $(info "1st")
  10. make -C $(KDIR) M=$(PWD) modules
  11. clean:
  12. rm -f *.ko *.o *.mod .*.cmd *.symvers *.mod.c *.mod.o *.order .hello*
  13. endif

将obj-m设置为xmodule.o,并使xmodule.o依赖于hello.o.
执行make命令后,生成xmodule.ko, 而不是hello.ko,
安装命令: sudo insmod xmodule.ko
查看命令:lsmod,就会看到被安装名为xmodule的模块。

原文链接:http://www.cnblogs.com/xiongxuanwen/p/14707748.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号