8

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?

4
  • Is your C program a kernel module or a user-space program? You can use -I option of gcc. Commented Sep 30, 2014 at 8:02
  • kernel module. I add the '-I/usr/src/linux-headers-2.6.32-38-server/include/' option to my Makefile, but after that the system continue with the compilation process, is this change enough? Commented Sep 30, 2014 at 8:28
  • If it is a kernel module you must use the kernel Makefile present in the kernel source directory. Why are you using gcc? Post the Makefile you are using to build the kernel module. Commented Sep 30, 2014 at 8:58
  • I have also user-space program in my project. iqstatic solve my problem. Commented Oct 1, 2014 at 6:16

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

2 Comments

I've got linkage.h:8:10: fatal error: asm/linkage.h: No such file or directory
same here. Anyone came up with a solution ?
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.