环境
root@T:/media/sf_D_DRIVE/kmodule/01_basic# cat /etc/os-release
PRETTY_NAME="Ubuntu 22.04.1 LTS"
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.1 LTS (Jammy Jellyfish)"
VERSION_CODENAME=jammy
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=jammy
Makefile
root@T:/media/sf_D_DRIVE/kmodule/01_basic# cat Makefile
obj-m := basic.o
KERNEL_DIR := /usr/lib/modules/`uname -r`/build
modules:
$(MAKE) -C $(KERNEL_DIR) M=$(PWD) modules
clean:
rm -f *.o *.ko *.mod *.mod.c *.order *.symvers
basic.c
root@T:/media/sf_D_DRIVE/kmodule/01_basic# cat basic.c
#include <linux/kernel.h>
#include <linux/module.h>#define TAG "HELLO# "
static int basic_init(void)
{
printk(TAG "%s called\n", __func__);
return 0;
}
static void basic_exit(void)
{
printk(TAG "%s called\n", __func__);
}module_init(basic_init);
module_exit(basic_exit);
MODULE_LICENSE("GPL");
运行效果
root@T:/media/sf_D_DRIVE/kmodule/01_basic# make
make -C /usr/lib/modules/`uname -r`/build M=/media/sf_D_DRIVE/kmodule/01_basic modules
make[1]: Entering directory '/usr/src/linux-headers-6.5.0-17-generic'
warning: the compiler differs from the one used to build the kernel
The kernel was built by: x86_64-linux-gnu-gcc-12 (Ubuntu 12.3.0-1ubuntu1~22.04) 12.3.0
You are using: gcc-12 (Ubuntu 12.3.0-1ubuntu1~22.04) 12.3.0
CC [M] /media/sf_D_DRIVE/kmodule/01_basic/basic.o
MODPOST /media/sf_D_DRIVE/kmodule/01_basic/Module.symvers
LD [M] /media/sf_D_DRIVE/kmodule/01_basic/basic.ko
BTF [M] /media/sf_D_DRIVE/kmodule/01_basic/basic.ko
Skipping BTF generation for /media/sf_D_DRIVE/kmodule/01_basic/basic.ko due to unavailability of vmlinux
make[1]: Leaving directory '/usr/src/linux-headers-6.5.0-17-generic'
root@T:/media/sf_D_DRIVE/kmodule/01_basic# insmod basic.ko
root@T:/media/sf_D_DRIVE/kmodule/01_basic# dmesg
[17191.831328] HELLO# basic_init called
root@T:/media/sf_D_DRIVE/kmodule/01_basic#