zoukankan      html  css  js  c++  java
  • linux内核模块编译-通过Makefile重命名.ko文件名和模块名

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

    #include <linux/module.h>
    #include <linux/kernel.h>
    #include <linux/fs.h>
    #include <linux/init.h>
    #include <linux/delay.h>
    
    #define HELLO_MAJOR 231
    #define DEVICE_NAME "HelloModule"
    
    static int hello_open(struct inode *inode, struct file *file)
    {
    	printk(KERN_EMERG "hello open.
    ");
    	return 0;
    }
    
    static ssize_t hello_write(struct file *file, const char __user *buf,
    			   size_t count, loff_t *ppos)
    {
    	printk(KERN_EMERG "hello write.
    ");
    	return 0;
    }
    
    static struct file_operations hello_flops = {
    	.owner = THIS_MODULE,
    	.open = hello_open,
    	.write = hello_write,
    };
    
    static int __init hello_init(void)
    {
    	int ret;
    	ret = register_chrdev(HELLO_MAJOR, DEVICE_NAME, &hello_flops);
    	if (ret < 0) {
    		printk(KERN_EMERG DEVICE_NAME
    		       " can't register major number.
    ");
    		return ret;
    	}
    	printk(KERN_EMERG DEVICE_NAME " initialized.
    ");
    	return 0;
    }
    
    static void __exit hello_exit(void)
    {
    	unregister_chrdev(HELLO_MAJOR, DEVICE_NAME);
    	printk(KERN_EMERG DEVICE_NAME " removed.
    ");
    }
    
    module_init(hello_init);
    module_exit(hello_exit);
    MODULE_LICENSE("GPL");
    

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

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

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

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

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

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

  • 相关阅读:
    AnaConda环境下安装librosa包超时
    [浙江大学数据结构]多项式求值,及算法效率问题
    java正则表达式测试用例
    tK Mybatis 通用 Mapper 3.4.6: Example 新增 builder 模式的应用
    Detect image format in Java(使用java探测图片文件格式)
    使用ColumnType注解解决/过滤/转义tk mybatis插入insertSelective、insert语句中遇到sql关键字
    IDEA中关闭sonar代码质量检测
    pip设置安装源
    无法修正错误,因为您要求某些软件包保持现状,就是它们破坏了软件包间的依赖关系
    sql 查出一张表中重复的所有记录数据
  • 原文地址:https://www.cnblogs.com/xiongxuanwen/p/14707748.html
Copyright © 2011-2022 走看看