linux ko
文章出自个人博客https://applelin8.github.io/2020/12/15/linux-ko,转载请申明
content
highlight
linux 系统ko模块编译。 note:
-
kernel dir
-
Makefile Kbuild Makefile 的一个最主要功能就是指定编译什么,这个功能是通过下面两个对象指定的obj-? 和$(module_name)-objs 例如:
obj-y += example.o #编译o
obj-m += $(module_name).o #编译ko
$(module_name)-objs := a.o b.o c.o #编译基于的目标文件a.o b.o c.o
makefile的关键:
首先 obj-m指定模块名 $(module_name),
obj-m := $(module_name).o
然后,
如果内核模块是通过几个源文件编译而成的,
再根据模块名$(name)-objs:=依赖的文件。
$(module_name)-objs := a.o b.o c.o
Makefile example
.PHONY: clean all
#variable
KDIR:=~/apple/kernel-4.15.4
MAKE:=make
name:=demo
#$(info name=$(name))
ifneq ($(KERNELRELEASE),)
obj-m:=$(name).o
$(name)-objs:= main.o hello.o
endif
#target
all: demo
demo:
#$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
$(MAKE) -C $(KDIR) M=$(PWD) modules
#sudo $(KDIR)/scripts/sign-file sha512 $(KDIR)/certs/signing_key.pem $(KDIR)/certs/signing_key.x509 $(name).ko
hello:
@echo hello
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
-
查看输出
dmesg | grep "keywords"
code
#ls demo
hello.c hello.h main.c Makefile
hello.h
#ifndef _LINUX_HELLO_H_
#define _LINUX_HELLO_H_
void hello(void);
#endif
hello.c
#include "hello.h"
#include <linux/kernel.h>
void hello(void)
{
printk("demo: hello\n");
printk("demo: happy day!\n");
}
main.c
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include "hello.h"
static int demo_init(void)
{
printk("demo: init module");
hello();
return 0;
}
static void demo_exit(void)
{
printk("demo: exit module");
return;
}
module_init(demo_init);
module_exit(demo_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("apple");
make
#cd demo
#make
make -C ~/apple/kernel-4.15.4 M=~/apple/project/module/demo modules
make[1]: Entering directory '~/apple/kernel-4.15.4'
CC [M] ~/apple/project/module/demo/main.o
CC [M] ~/apple/project/module/demo/hello.o
LD [M] ~/apple/project/module/demo/demo.o
Building modules, stage 2.
MODPOST 1 modules
CC ~/apple/project/module/demo/demo.mod.o
LD [M] ~/apple/project/module/demo/demo.ko
make[1]: Leaving directory '~/apple/kernel-4.15.4'
#ls ../demo
demo.ko demo.mod.c demo.mod.o demo.o hello.c hello.h hello.o main.c main.o Makefile modules.order Module.symvers
#lsmod|grep demo
demo 16384 0
#sudo rmmod demo
#sudo insmod demo.ko
#dmesg|grep demo
[ 2109.050790] demo: init module
[ 2109.050792] demo: hello
[ 2109.050793] demo: happy day!
#sudo rmmod demo
#dmesg|grep demo
[ 2123.678684] demo: exit module
make clean
#make clean
make -C ~/apple/kernel-4.15.4 M=~/apple/project/module/demo clean
make[1]: Entering directory '~/apple/kernel-4.15.4'
CLEAN ~/apple/project/module/demo/.tmp_versions
CLEAN ~/apple/project/module/demo/Module.symvers
make[1]: Leaving directory '~/apple/kernel-4.15.4'
评论:
技术文章推送
手机、电脑实用软件分享
微信公众号:farmer in city