c - 使用具有不同路径名的 Makefile 构建 Linux 内核模块

标签 c linux makefile linux-kernel

我正在尝试使用 Linux Kernel Module Programming Guide 中指定的标准示例 Makefile 编译 Linux 内核模块.如果 Makefile 名为 Makefile,那么一切正常。如果我将 Makefile 重命名为 Makefile.hello 或其他名称,那么它将失败,因为它找不到路径 Makefile。我想知道是否有一个命令或一组标志可以添加到我的 Makefile 中以正确执行此功能。我需要重命名 Makefile,因为我正在从 CMake 调用它。 Cmake 会创建自己的 Makefile,并且通常会覆盖我已有的内容。

我用 hello world 示例替换了内核模块代码并重现了问题。我知道它的生成文件。

Hello World 示例 hello.c

/*
 * hello−1.c − The simplest kernel module.
 */
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
int init_module(void)
{
    printk(KERN_INFO "Hello world 1.\n");
    /*
     * A non 0 return means init_module failed; module can't be loaded.
     */
    return 0;
}
void cleanup_module(void)
{
    printk(KERN_INFO "Goodbye world 1.\n");
}

生成文件

obj-m += hello.o

ifeq (,$(KDIR))
    KDIR := /lib/modules/$(shell uname -r)/build
endif

PWD := $(shell pwd)

all:
    $(MAKE) -C $(KDIR) M=$(PWD) $(KCONFIG) modules

clean:
    $(MAKE) -C $(KDIR) M=$(PWD) clean

如果生成文件称为Makefile。 (构建成功)

$> make -f Makefile
make -C /lib/modules/4.4.0-21-generic/build M=/home/msmith/Desktop/kernel-test  modules
make[1]: Entering directory '/usr/src/linux-headers-4.4.0-21-generic'
  CC [M]  /home/msmith/Desktop/kernel-test/hello.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /home/msmith/Desktop/kernel-test/hello.mod.o
  LD [M]  /home/msmith/Desktop/kernel-test/hello.ko
make[1]: Leaving directory '/usr/src/linux-headers-4.4.0-21-generic'

如果 makefile 被调用则输出 Makefile.hello(构建失败)

$> make -f Makefile.hello
make -C /lib/modules/4.4.0-21-generic/build M=/home/msmith/Desktop/kernel-test  modules
make[1]: Entering directory '/usr/src/linux-headers-4.4.0-21-generic'
scripts/Makefile.build:44: /home/msmith/Desktop/kernel-test/Makefile: No such file or directory
make[2]: *** No rule to make target '/home/msmith/Desktop/kernel-test/Makefile'.  Stop.
Makefile:1396: recipe for target '_module_/home/msmith/Desktop/kernel-test' failed
make[1]: *** [_module_/home/msmith/Desktop/kernel-test] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-4.4.0-21-generic'
Makefile.hello:10: recipe for target 'all' failed
make: *** [all] Error 2

我尝试将 -f 添加到内部 MAKE 参数,但这只会导致更多问题。

最佳答案

将所有与 Kbuild 相关的逻辑移动到文件 Kbuild 中。内核的构建系统首先检查具有此名称的文件,因此它不会查看由 CMake 创建的 Makefile。此功能记录在 Documentation/kbuild/makefiles.txt 中.

我在与 Linux 内核相关的 CMake 项目中使用了这种方法。

关于c - 使用具有不同路径名的 Makefile 构建 Linux 内核模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37553169/

相关文章:

c++ - 构建可执行文件时找不到 pthread 库?

c++ - 使用 pThreads 在线程之间共享 3D 数组

c - 如何用C语言创建矩阵结构?

linux - 在保护我的网络服务器(rpi)免受外部 ssh 登录的影响后,我在我的计算机上发现了这个 perl 脚本。有人能告诉我它有什么作用吗?

python - 为 input() 函数输入数据时箭头键不起作用

qt - 在Windows中编译OpenCV SVN干线-highgui/libVideoInput中的错误

c - 合成器 - 记录按下的键盘

c - Ceil 和整数的使用

python - 是否可以与/dev/bus/usb/<bus>/<device> 进行串行通信

c - 目标文件缺少函数符号