Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 806
kobi Avatar asked Sep 30 '14 06:09

kobi


People also ask

How do I compile only one kernel module?

create new folder somewhere for the module source (example: extra) and copy only source files (from the kernel source or somewhere else) related to the module needed to be build into this new folder. copy /boot/config-`uname -r` file (example: /boot/config-4.8. 0-46-generic) into kernel source folder file .

Is the Linux kernel compiled with GCC?

The Linux kernel to now supported building on kernels as far back as GCC 4.9 while now it has been bumped to GCC 5.1. AArch64 already required at least GCC 5.1 while this bump affects all other architectures.


Video Answer


2 Answers

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

like image 51
user31986 Avatar answered Oct 10 '22 06:10

user31986


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.

like image 44
iqstatic Avatar answered Oct 10 '22 06:10

iqstatic