How to compile a kernel module for Raspberry pi?

user3025582 picture user3025582 · Nov 23, 2013 · Viewed 69.3k times · Source

I'm having trouble compiling a kernel module for a raspberry pi. I want to compile a "hello world" kernel module using the raspberry pi itself.

I am using raspbian wheezy 3.6.11+.

I tried following the directions at http://elinux.org/RPi_Kernel_Compilation.

Here is the Makefile I am using:

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

Here is the source code for 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");
}

Here's what I get when I try to make the project:

root@raspberrypi:/home/pi/hello-module# make
make -C /lib/modules/3.6.11+/build M=/home/pi/hello-module modules
make: *** /lib/modules/3.6.11+/build: No such file or directory.  Stop.
make: *** [all] Error 2

I tried creating the build directory at /lib/modules/3.6.11+

make -C /lib/modules/3.6.11+/build M=/home/pi/hello-module modules
make[1]: Entering directory `/lib/modules/3.6.11+/build'
make[1]: *** No rule to make target `modules'.  Stop.
make[1]: Leaving directory `/lib/modules/3.6.11+/build'
make: *** [all] Error 2

I have GNU Make 3.81 and gcc (Debian 4.6.3-14+rpi1) 4.6.3 installed. I also installed the linux source using

sudo apt-get install linux-source

Any ideas on what I might do to get this to compile?

Answer

Greg picture Greg · Jan 10, 2014

When compiling a module the -C parameter should point to the source tree where the kernel was built (don't clean it up!). If you built it on the pi its likely in a directory under your home directory.

The build directory under /lib/modules/<version> is a Debian-ism, where a cut-down version of the source tree is provided with just enough context to build modules against. The kernels from the Raspberry Pi Foundation kernels don't ship with a build directory.

They may be a bit out of date, but raspbian provides a kernel as a Debian-style package, which should include the build directory you could use to build kernel modules against.

sudo aptitude install linux-image-rpi-rpfv linux-headers-rpi-rpfv