Ubuntu添加内核模块时Makefile编译报错:缺少hello.c文件
Hey there, let's troubleshoot that kernel module build error you're facing. I've seen this exact issue before, so let's break it down and fix it step by step.
First, let's recap what you're working with:
Your Makefile:
obj-m += hello.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
The Error You Got:
make -C /lib/modules/4.4.0-31-generic/build M=/home/fast modules make[1]: Entering directory '/usr/src/linux-headers-4.4.0-31-generic' make[2]: *** No rule to make target '/home/fast/hello.c', needed by '/home/fast/hello.o'. Stop. Makefile:1403: recipe for target '_module_/home/fast' failed make[1]: *** [_module_/home/fast] Error 2 make: *** [all] Error 2
What's Causing This?
The error is straightforward: the kernel build system can't find your hello.c source file. When you define obj-m += hello.o in your Makefile, Kbuild (the kernel's build system) expects a corresponding hello.c file in the same directory to compile into hello.o. Without that source file, it doesn't know how to create the object file, hence the "No rule to make target" error.
Step-by-Step Fixes:
Create the required
hello.csource file
You need a minimal kernel module source code file namedhello.cin the same directory as your Makefile. Here's a working example you can copy-paste:#include <linux/init.h> #include <linux/module.h> MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Hello World Kernel Module"); static int __init hello_init(void) { printk(KERN_INFO "Hello, kernel!\n"); return 0; } static void __exit hello_exit(void) { printk(KERN_INFO "Goodbye, kernel!\n"); } module_init(hello_init); module_exit(hello_exit);Double-check file locations
Make sure bothMakefileandhello.care in/home/fast(the directory you're runningmakefrom). Verify this with:ls /home/fastYou should see both files listed here.
Re-run the build command
Head back to the directory and runmakeagain:cd /home/fast makeIf everything is set up correctly, you'll see the build process complete successfully, and you'll find a
hello.kofile (your kernel module) in the directory.Quick sanity check: Ensure kernel headers are installed
While your current error isn't about missing headers, it's a good idea to confirm you have the right headers for your kernel version. If you don't, install them with:sudo apt-get install linux-headers-$(uname -r)
内容的提问来源于stack exchange,提问作者user8181313

