我们如何在C中编译内核代码?

Wan*_*rer 5 c linux gcc

我是C和Linux的新手.我正在尝试编译下面的代码,但它在编译时会给出一些致命的错误.任何帮助修复这个赞赏.

这是代码measurecpu.c:

#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));

}
Run Code Online (Sandbox Code Playgroud)

我试图以这种方式编译它:

gcc -c -O2 -W -Wall -isystem /lib/modules/'uname -r'/build/include -D_KERNEL_ -DMODULE measurecpu.c
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

measurecpu.c:1:32: fatal error: linux/module.h: No such file or directory
 #include <linux/module.h>      
                                ^
compilation terminated.
Run Code Online (Sandbox Code Playgroud)

art*_*rtm 5

我试图用这种方式编译它gcc -c -O2 -W -Wall -isystem/lib/modules /'uname -r'/ build/include -D_KERNEL_ -DMODULE measurecpu.c

通常编译内核模块的方法是使用内核构建系统 - 即您使用make而不是gcc直接使用.您需要创建一个Makefile并指定对象,这是obj-m := measurecpu.o您的案例中的行.之后在同一目录中,发出make命令,这将产生内核对象文件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
Run Code Online (Sandbox Code Playgroud)

请注意,内核模块不是用户空间程序,因此您不能只运行它.您需要通过内核告知内核该内核模块insmod,并通过查看结果dmesg.