【问题标题】:How do we compile kernel code in C?我们如何在 C 中编译内核代码?
【发布时间】:2016-01-24 20:11:22
【问题描述】:

我是 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));

}

我正在尝试这样编译:

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

我收到此错误:

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

【问题讨论】:

  • 如果出现构建错误,则不会出现分段错误。
  • 哎呀,我的意思是我们如何构建代码。抱歉措辞错误。将编辑
  • /lib/modules/'uname -r'/build/include backticks 在这里。或者使用 $(uname -r)。 'uname -r' 将只是那个字符串,不执行替换。

标签: c linux gcc


【解决方案1】:

我正在尝试以这种方式编译它 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

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

【讨论】:

    【解决方案2】:

    正如错误消息中明确指出的那样,编译器在文件夹linux 中找不到头文件module.h

    参考这个帖子:error compiling: linux/module.h: No such file or directory

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      • 2019-11-20
      • 2022-07-07
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2016-10-08
      相关资源
      最近更新 更多