Kernel compile "Hello world"

Compile minimal linux kernel module.

Files

You need to create to files Makefile and hello_world.c.

Makefile

1
2
3
4
5
6
7
8
9
obj-m += hello_world.o

KDIR ?= /lib/modules/$(shell uname -r)/build

all:
	make -C $(KDIR) M=$(PWD) modules

clean:
	make -C $(KDIR) M=$(PWD) clean

hello_world.c

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
//http://www.tldp.org/LDP/lkmpg/2.4/html/c147.htm
#include <linux/module.h>  /* Needed by all modules */
#include <linux/kernel.h>

int hello_world_init( void )
{
	printk(KERN_DEBUG "Hello World!\n");
	return 0;
}

void hello_world_exit( void )
{
	printk(KERN_DEBUG "Exit Hello World!\n");
}

module_init( hello_world_init );
module_exit( hello_world_exit );

MODULE_LICENSE("GPL");

Compile

Now if you havent done so ... install kernel headers of kernel that your system have now. And everything should be there.

1
make

Load module

1
sudo insmod hello_world.ko

check that module is running

1
lsmod | grep hello

Unload module

1
rmmod hello_world

Install kernel headers raspbian

RaspberryPi4 ARMv8

1
sudo apt-get install raspberrypi-kernel-headers