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的模块。

  • 相关阅读:
    bootstrap
    前端框架 angularjs
    JAva集合框架
    圣诞
    IDEA
    科目三
    Bootstrap简介及Bootstrap里的栅格系统col-md/sm/xs-x;
    C# Windows service 定时发邮件功能 (用到webService)
    <转> 数据库索引的作用和优点缺点
    小知识
  • 原文地址:https://www.cnblogs.com/xiongxuanwen/p/14707748.html
Copyright © 2011-2022 走看看