kobi
kobi

Reputation: 341

Compiling Linux kernel module using gcc with kernel header files

I have a Linux machine with kernel A header files. I want to compile a C program using GCC with kernel A while kernel B is currently running.

How can I do that? How do I check that it works?

Upvotes: 8

Views: 17219

Answers (2)

user31986
user31986

Reputation: 1656

This is additional info to delve into. Post 2.6 version, as mentioned in other reply the Makefile takes care of most of the Linux kernel module compilation steps. However, at the core of it is still GCC, and this is how it does: (you too may compile it without Makefile)

Following GCC options are necessary:

  1. -isystem /lib/modules/`uname -r`/build/include: You must use the kernel headers of the kernel you're compiling against. Using the default /usr/include/linux won't work.

  2. -D__KERNEL__: Defining this symbol tells the header files that the code will be run in kernel mode, not as a user process.

  3. -DMODULE: This symbol tells the header files to give the appropriate definitions for a kernel module.

gcc -DMODULE -D__KERNEL__ -isystem /lib/modules/$(uname -r)/build/include -c hello.c -o hello.ko

Upvotes: 10

iqstatic
iqstatic

Reputation: 2382

In order to compile a kernel module, it is better to use the kernel Makefile resident in the Kernel source directory. You can use the following make command:

make -C $(KERNEL_SOURCE_DIR) M=`pwd` modules

Otherwise, you can choose to write your own Makefile like this:

KERNEL_DIR := /lib/modules/$(shell uname -r)/build

obj-m := test.o

driver:
    make -C $(KERNEL_DIR) M=`pwd` modules

clean:
    make -C $(KERNEL_DIR) M=`pwd` clean

In this I have used the KERNEL_DIR as /lib/modules/$(shell uname -r)/build which uses the kernel headers of the kernel which is running currently. However, you can use the path of the kernel source directory you want to compile your module with.

This shows how you can do it using gcc.

Upvotes: 5

Related Questions