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.\n");
	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.\n");
	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.\n");
		return ret;
	}
	printk(KERN_EMERG DEVICE_NAME " initialized.\n");
	return 0;
}

static void __exit hello_exit(void)
{
	unregister_chrdev(HELLO_MAJOR, DEVICE_NAME);
	printk(KERN_EMERG DEVICE_NAME " removed.\n");
}

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM