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?
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 .
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.
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:
-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.
-D__KERNEL__: Defining this symbol tells the header files that the code will be run in kernel mode, not as a user process.
-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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With