我们如何用C语言编译内核代码?
我不熟悉C和Linux。我正在尝试编译下面的代码,但在编译时出现了一些致命错误。任何关于修复此问题的帮助都将不胜感激 下面是代码我们如何用C语言编译内核代码?,c,linux,gcc,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/preem
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));
}
我得到这个错误:
measurecpu.c:1:32: fatal error: linux/module.h: No such file or directory
#include <linux/module.h>
^
compilation terminated.
measurecpu.c:1:32:致命错误:linux/module.h:没有这样的文件或目录
#包括
^
编译终止。
我正试图以这种方式编译它
gcc-c-O2-W-Wall-isystem/lib/modules/'uname-r'/build/include-D_内核u-D模块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
请注意,内核模块不是用户空间程序,所以您不能只运行它。您需要通过
insmod
告诉内核关于该内核模块的信息,并通过dmesg
检查结果,因为错误消息清楚地表明,编译器在linux
文件夹中找不到头文件module.h
请参阅本文:如果出现构建错误,则无法获得分段错误。哎呀,我的意思是如何构建代码。对不起,用错了词。将编辑/lib/modules/'uname-r'/build/include
# 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