How to compile kernel code in C?

I am new to C and Linux. I am trying to compile the code below, but when compiling it gives some fatal error. Any help in fixing this was appreciated.

Here is the measurecpu.c code:

 #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/hardirq.h> #include <linux/preempt.h> #include <linux/sched.h> #include<stdio.h> int main() { uint64_t start, end; int i=0; asm volatile ("CPUID \ n \ t" "RDTSC \ n \ t" "mov %%edx, %0 \ n \ t" "mov %%eax, %1 \ n \ t": "=r" (cycles_high), "=r" (cycles_low):: "%rax", "%rbx", "%rcx", "%rdx"); for(i=0; i<200000;i++) {} asm volatile ("RDTSCP \ n \ t" "mov %%edx, %0 \ n \ t" "mov %%eax, %1 \ n \ t" "CPUID \ n \ t": "=r" (cycles_high1), "=r" (cycles_low1):: "%rax", "%rbx", "%rcx", "%rdx"); start = ( ((uint64_t)cycles_high << 32) | cycles_low ); end = ( ((uint64_t)cycles_high1 << 32) | cycles_low1 ); printk(KERN_INFO " \ n function execution time is %llu clock cycles",(end - start)); } 

I am trying to compile it as follows:

 gcc -c -O2 -W -Wall -isystem /lib/modules/'uname -r'/build/include -D_KERNEL_ -DMODULE measurecpu.c 

I get this error:

 measurecpu.c:1:32: fatal error: linux/module.h: No such file or directory #include <linux/module.h> ^ compilation terminated. 
+5
source share
2 answers

I am trying to compile it this way gcc -c -O2 -W -Wall -system / lib / modules / 'uname -r' / build / include -D_KERNEL_ -DMODULE measurecpu.c

Usually, a way to compile a kernel module is to use a kernel build system, i.e. use make instead of gcc directly. You need to create a Makefile and specify an object that is the string obj-m := measurecpu.o in your case. After that, in the same directory, run the make , which will give the kernel object file measurecpu.ko

 # If KERNELRELEASE is defined, we've been invoked from the # kernel build system and can use its language. ifneq ($(KERNELRELEASE),) obj-m := measurecpu.o # Otherwise we were called directly from the command # line; invoke the kernel build system. else KERNELDIR ?= /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) default: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules clean: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules clean endif 

Note that the kernel module is not a user space program, so you cannot just start it. You will need to tell the kernel about this kernel module through insmod and check the results with dmesg .

+5
source

As the error message clearly states, the compiler could not find the module.h header file in the linux folder.

Refer to this post: error compilation: linux / module.h: No such file or directory

+1
source

Source: https://habr.com/ru/post/1241367/


All Articles