Create both files in the same directory.
hello.c
#include <linux/init.h>
#include <linux/module.h>
static int __init hello_init(void)
{
pr_info("hello_lab: loaded\n");
return 0;
}
static void __exit hello_exit(void)
{
pr_info("hello_lab: unloaded\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
Makefile
obj-m := hello.o
Build and verify
In the QEMU guest, change to the source directory. Confirm that the build succeeds before loading the module.
make -C "/lib/modules/$(uname -r)/build" M="$PWD" modules
modinfo -F vermagic ./hello.ko
sudo insmod ./hello.ko
sudo rmmod hello
sudo dmesg | grep 'hello_lab:' | tail -n 2
Expect hello_lab: loaded followed by hello_lab: unloaded. The macros module_init() and module_exit() identify the callbacks Linux invokes when it loads and unloads the module.
Exercise
Include <linux/errno.h> and return -EINVAL from hello_init(). Rebuild and run insmod again. Insertion should fail without a new unloaded entry. If initialization acquires resources before failing, release them on the initialization error path.