How to compile Linux kernel modules

Example: hello.c module

1) hello.c – It is C source code. Copy following code and save to hello.c
$ mkdir demo; cd demo
$ vi hello.c

2)Add following c source code to it:

#include <linux/module.h>       /* Needed by all modules */
#include <linux/kernel.h>       /* Needed for KERN_INFO */
#include <linux/init.h>         /* Needed for the macros */

static int __init hello_start(void)
{
printk(KERN_INFO "Loading hello module...\n");
printk(KERN_INFO "Hello world\n");
return 0;
}

static void __exit hello_end(void)
{
printk(KERN_INFO "Goodbye Mr.\n");
}

module_init(hello_start);
module_exit(hello_end);

This is an example modified from original source for demonstration purpose.

3) Save the file. Create new Makefile as follows:
$ vi Makefile
Append following make commands:

obj-m = hello.o
KVERSION = $(shell uname -r)
all:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean

4) Save and close the file.

5) Compile hello.c module:
$ make

6) Become a root user (use su or sudo) and load the module:
$ su -
# insmod hello.ko

If you get error message:

insmod: ERROR: could not insert module hello.ko: Invalid module format

then reinstall kernel headers with:

sudo apt update && sudo apt upgrade
sudo apt remove --purge linux-headers-*
sudo apt autoremove && sudo apt autoclean
sudo apt install linux-headers-generic

Note you can see message on screen if you are logged in as root under run level 3.

7) Verify that module loaded using the lsmod command:
# lsmod | less

8) See message in /var/log/message file using the tail command or less command:
# tail -f /var/log/syslog

9) Unload the module using the rmmod command:
# rmmod hello

10) Load module when Linux system comes up. File /etc/modules use to load kernel boot time. This file should contain the names of kernel modules that are to be loaded at boot time, one per line. First copy your module to /lib/modules/$(uname -r)/kernel/drivers. Following are suggested steps:

(a) Create directory for hello module:
# mkdir -p /lib/modules/$(uname -r)/kernel/drivers/hello
(b) Copy module:
# cp hello.ko /lib/modules/$(uname -r)/kernel/drivers/hello/
(c) Edit /etc/modules file under Debian Linux:
# vi /etc/modules
(d) Add following line to it:
hello
(e) Reboot to see changes. Use lsmod or dmesg command to verify module loaded or not.
cat /proc/modules
OR
# lsmod | less

 

Source: How to compile Linux kernel modules – nixCraft

How to compile Linux kernel modules was last modified: June 5th, 2023 by Jovan Stosic

Leave a Reply