构建 linux 内核模块

Building linux kernel module

我是 windows 驱动程序程序员,是 linux 内核的新手 development.I 已经安装了 linux 内核头文件。我正在 linux 内核中尝试我的 helloworld 模块。

#include <linux/init.h>
#include <linux/module.h>
/*MODULE_LICENSE("Dual BSD/GPL");*/
static int hello_init(void)
{
    printk(KERN_ALERT "Hello, world\n");
    return 0;
}
static void hello_exit(void)
{
    printk(KERN_ALERT "Goodbye, cruel world\n");
}
module_init(hello_init);
module_exit(hello_exit);

以下是我的模块的代码。我构建的 makefile 是

obj-m +=tryout.o

KDIR =/usr/src/linux-headers-4.13.0-37-generic

all:
    $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
clean:
    rm -rf *.o *.ko *.mod.* *.symvers *.order

但我越来越 'fatal error: linux/init.h: No such file or directory while making this module'。可能的原因是什么?我该如何解决?

您的 Makefile 是 mis-configured。特别是你使用 SUBDIRS 而你应该使用 M 而你的 $(PWD) 是没有意义的,你应该使用 pwd 来简单(或 $$PWD);设置方法如下:

    ifneq ($(KERNELRELEASE),)
    # kbuild part of makefile
    obj-m  := tryout.o
    # any other c files that you would like to include go into 
    # yourmodule-y := <here> e.g.:

    # tryout-y := tryout-1.o tryout-2.o 

    else
    # normal makefile
    KDIR ?= /usr/src/linux-headers-4.13.0-37-generic

    # you really should set KDIR up as:
    # KDIR := /lib/modules/`uname -r`/build

    all::
        $(MAKE) -C $(KDIR) M=`pwd` $@

    # Any module specific targets go under here
    # 

    endif

像这样配置您的 makefile 将允许您在模块目录中简单地键入 make,它将调用内核的 kbuild 子系统,该子系统将 in-turn 使用 kbuild 你的 Makefile 的一部分。

阅读 https://www.kernel.org/doc/Documentation/kbuild/modules.txt,了解有关如何执行此操作的所有不同排列。它带有示例。