How to make a simple linux kernel module

Although monolithic kernel faster than a micro-kernel  but it has disadvantage of lack modularity and extendsibility.

On modern monolithic kernels, this problem has been resolved  by using kernel modules. A linux kernel module is an object file that contains code that can extend the kernel functionality at run-time. Most of the device drivers are used in the form of linux kernel modules.

An example of a linux kernel module

We will create a simple C program as below with name is helloworld.c. When loading into the kernel, it will generate the message "Hello world". When unloading the kernel module, the "Bye bye"message will be generated.


#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>

MODULE_DESCRIPTION("Simple kernel module");

static int __init simple_init(void)
        pr_debug("Hello, world!\n");
        return 0;

static void __exit simple_exit(void)
        pr_debug("Bye bye!\n");


Compiling linux kernel module

In order to compile a linux kernel module, we will create a make file


obj-m += helloworld.o
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

When we run “make”, it should compile your module successfully. The resulting file is “helloworld.ko”

linux kernel module
                                                          1. Compiling linux kernel module

Loading a linux kernel module

Now we can insert the module to test it. To do this, run:

sudo insmod helloworld.ko

If all goes well, you won’t see a thing. The printk function doesn’t output to the console but rather the kernel log. To see that, we’ll need to run:

sudo dmesg
linux kernel module
                                                   2. Loading linux kernel module

You should see the “Hello, World!” line prefixed by a timestamp. This means our linux  kernel module loaded and successfully printed to the kernel log. We can also check to see if the module is still loaded:

lsmod | grep “helloworld”

To remove the module, run:

sudo rmmod helloworld
linux kernel module
                                                            3. Unloading linux kernel module

If you run dmesg again, you’ll see “Bye bye!” in the logs. You can also use lsmod again to confirm it was unloaded.


I hope you’ve enjoyed our romp through kernel land. Though the examples I’ve provided are basic, you can use this structure to construct your own module that does very complex tasks.

0 thoughts on “How to make a simple linux kernel module

  1. Pingback: [Linux kernel]How to make a simple character device drivers – NZ REVIEW – BEST SOFTWARE FOR WORK

Add Comment