我的系统:
gyz@debian:~/der$ uname -a
Linux debian 4.19.0-0.bpo.2-amd64 #1 SMP Debian 4.19.16-1~bpo9+1 (2019-02-07) x86_64 GNU/Linux
gyz@debian:~/der$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description: Debian GNU/Linux 9.8 (stretch)
Release: 9.8
Codename: stretch
注意:
我这个是在linux系统上写的,所以用的是linux自己的内核源码,如果你是往开发板上移植,就用开发板上系统内核源码,并且用交叉编译器。
1,hello.c源码如下:
/*所有的模块带啊吗都要包含这两个头文件*/
#include <linux/module.h>
#include <linux/init.h>
/*代码所使用的许可证*/
MODULE_LICENSE("Dual BSD/GPL");
/*初始化代码*/
static int initialization_function(void)
{
printk(KERN_ALERT "hello world!\n");
return 0;
}
/*清除函数*/
static void cleanup_function(void)
{
printk(KERN_ALERT "bye world!\n");
}
module_init(initialization_function);
module_exit(cleanup_function);
2,makefile文件内容
obj-m += hello.o
KERNEL_DIR += /lib/modules/$(shell uname -r)/build
PWD += $(shell pwd)
all:
make -C $(KERNEL_DIR) SUBDIRS=$(PWD) modules
# make -C $(KERNEL_DIR) hello.c modules
clean:
rm *.o *.ko *.mod.c
.PHONY:clean
-C指定内核源码文件目录,SUBDIRS指需要编译的.c文件的路径。
3,编译
gyz@debian:~/der$ make
make -C /lib/modules/4.19.0-0.bpo.2-amd64/build SUBDIRS=/home/gyz/der /home/gyz/der modules
make[1]: Entering directory '/usr/src/linux-headers-4.19.0-0.bpo.2-amd64'
make[3]: Nothing to be done for '/home/gyz/der'.
Building modules, stage 2.
MODPOST 1 modules
make[1]: Leaving directory '/usr/src/linux-headers-4.19.0-0.bpo.2-amd64'
4,安装/显示/卸载模块
gyz@debian:~/der$ su -
密码:
root@debian:~# cd /home/gyz/der/
root@debian:/home/gyz/der# ls
hello.c hello.mod.c hello.o Makefile Module.symvers
hello.ko hello.mod.o m2 modules.order
root@debian:/home/gyz/der# insmod hello.ko
insmod: ERROR: could not insert module hello.ko: File exists
root@debian:/home/gyz/der# rmmod hello.ko
root@debian:/home/gyz/der# insmod hello.ko
root@debian:/home/gyz/der# lsmod | grep "hello"
hello 16384 0
root@debian:/home/gyz/der# rmmod hello.ko
root@debian:/home/gyz/der# lsmod | grep "hello"
root@debian:/home/gyz/der# dmesg | tail -6
[114720.199139] hello world!
[114739.031534] bye world!
[116357.767541] hello world!
[116889.978951] bye world!
[116900.055598] hello world!
[116925.801990] bye world!