Created: August, 28, 2023 Last Modified: August, 28, 2023

Building a Kernel Module on a Raspberry Pi

Installing Dependencies

First make sure your Pi is up to date

sudo apt update
sudo apt upgrade

Next lets install some needed dependencies for building

sudo apt install git bc bison flex libssl-dev

Now we can install the headers needed for building a linux module

sudo apt install raspberrypi-kernel-headers

Basic Kernel Module Source


Now lets create a basic kernel module to test everything is working. This example is taken from LDP

hello-1.c

/*  
 *  hello-1.c - The simplest kernel module.
 */
#include <linux/module.h>	/* Needed by all modules */
#include <linux/kernel.h>	/* Needed for KERN_INFO */

int init_module(void)
{
	printk(KERN_INFO "Hello world 1.\n");

	/* 
	 * A non 0 return means init_module failed; module can't be loaded. 
	 */
	return 0;
}

void cleanup_module(void)
{
	printk(KERN_INFO "Goodbye world 1.\n");
}

All the module does is use the kernel print to write hello on init, and goodbye on removal. Next let create a Makefile for convenience

Makefile

obj-m += hello-1.o

all:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

After creating those files run make which should start the build and output something like this

root@pg3-pizerow:~/hello_module# make
make -C /lib/modules/6.1.21+/build M=/root/hello_module modules
make[1]: Entering directory '/usr/src/linux-headers-6.1.21+'
  CC [M]  /root/hello_module/hello-1.o
  MODPOST /root/hello_module/Module.symvers
  CC [M]  /root/hello_module/hello-1.mod.o
  LD [M]  /root/hello_module/hello-1.ko
make[1]: Leaving directory '/usr/src/linux-headers-6.1.21+'

Now we can load the built module using insmod hello-1.ko and if we look in /var/log/messages you should see Hello World 1. When you are done you can remove the module using rmmod hello-1. With that you should now have a Raspberry Pi setup for kernel module development!