以下环境为 虚拟机为Ubuntu 22.04 。
sudo apt install linux-headers-`uname -r`
/*
* hello-1.c - The simplest kernel module.
*/
#include <linux/kernel.h> /* Needed for pr_info() */
#include <linux/module.h> /* Needed by all modules */
int init_module(void)
{
pr_info("Hello world 1.\n");
/* A non 0 return means init_module failed; module can't be loaded. */
return 0;
}
void cleanup_module(void)
{
pr_info("Goodbye world 1.\n");
}
MODULE_LICENSE("GPL");
Makefile
obj-m += a.o
PWD := $(CURDIR)
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
然后在当前目录打开终端,输入: make
开始编译。
如果编译报错,请确认没有设置有关交叉编译的环境变量。
然后make 成功之后
执行 sudo insmod a.ko
查看:
dmesg
就可以看到 Hello world 1