一、编写程序
新建文件夹 hello_module,创建hello_module.c文件,代码内容为:
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("SONGJL");
static int hello_init(void)
{
printk(KERN_EMERG "HELLO WORD SJL ENTER!\n");
return 0;
}
static void hello_exit(void)
{
printk(KERN_EMERG "HELLO WORD EXIT!\n");
}
module_init(hello_init);
module_exit(hello_exit);
创建Makefile文件,内容为:
#!/bin/bash
CROSS_COMPILE:= /home/forlinx/OK3399/OK3399-linux-release/prebuilts/gcc/linux-x86/aarch64/gcc-linaro-6.3.1-2017.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-
ARCH:= arm64
CC:= $(CROSS_COMPILE)gcc
LD:= $(CROSS_COMPILE)ld
PWD:= $(shell pwd)
obj-m := hello_module.o
KERNELDIR:= /home/forlinx/OK3399/OK3399-linux-release/kernel
all:
make -C $(KERNELDIR) M=$(PWD) modules
clean:
rm -f *.o
rm -f *.symvers
rm -f *.order
rm -f *.ko
rm -f *.mod.c
二、编译
在hello_module文件件夹下执行命令:
make
如果不出错,编译结果为:
make -C /home/forlinx/OK3399/OK3399-linux-release/kernel M=/home/project/hellomodule modules
make[1]: Entering directory '/home/forlinx/OK3399/OK3399-linux-release/kernel'
WARNING: Symbol version dump ./Module.symvers
is missing; modules will have no dependencies and modversions.
CC [M] /home/project/hellomodule/hello_module.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/project/hellomodule/hello_module.mod.o
LD [M] /home/project/hellomodule/hello_module.ko
make[1]: Leaving directory '/home/forlinx/OK3399/OK3399-linux-release/kernel'
查看目录下会发现:
root@sjl-virtual-machine:/home/project/hellomodule# ls
hello_module.c hello_module.ko hello_module.mod.c hello_module.mod.o hello_module.o Makefile modules.order Module.symvers
三、执行
将ko文件放入目标板内,可以通过HTTP Server.exe 或者TFTP将文件上传。
加载模块
sudo insmod hello_module.ko
查看模块
cat /proc/modules
或
lsmod
卸载模块
sudo rmmod hello_module
四、注意事项
编译过程中可能会报错
1、Makefile 文件编辑出错,回车键,还有tab键。可以在Linux环境下编写避免错误。
2、报这个错误
make[1]: Entering directory '/home/forlinx/OK3399/OK3399-linux-release/kernel'
ERROR: Kernel configuration is invalid.
include/generated/autoconf.h or include/config/auto.conf are missing.
Run 'make oldconfig && make prepare' on kernel src to fix it.
WARNING: Symbol version dump ./Module.symvers
is missing; modules will have no dependencies and modversions.
CC [M] /home/project/hellomodule/hello_module.o
In file included from <command-line>:0:0:
././include/linux/kconfig.h:4:32: fatal error: generated/autoconf.h: No such file or directory
#include <generated/autoconf.h>
^
compilation terminated.
scripts/Makefile.build:283: recipe for target '/home/project/hellomodule/hello_module.o' failed
解决办法:重新编译一下内核就好了。