Ubuntu16.04下内核模块编译失败求助
Hey there! Let's work through fixing your kernel module compilation problems together. I’ve spotted a handful of issues in your code, plus I’ll cover the proper build setup you need for Ubuntu 16.04.
Step 1: Fix the Critical Issues in Your
kernel_hello.c Code Your source code has a few syntax and structural mistakes that are causing compilation failures. Here's the corrected version, with explanations of each fix:
#include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> // Fixed: Added semicolons to all MODULE_* macros (required in C) MODULE_LICENSE("DUAL BSD/GPL"); MODULE_AUTHOR("YANQIN"); MODULE_DESCRIPTION("kernel module hello"); MODULE_VERSION("1.0"); static int hello_init(void) { printk(KERN_ALERT "hello_init() start\n"); return 0; } // Fixed: Corrected function parameter list (must be `void` for exit functions) // Added: Proper function body with a printk for exit feedback static void hello_exit(void) { printk(KERN_ALERT "hello_exit() called\n"); } // Fixed: Added required macros to register your init/exit functions with the kernel module_init(hello_init); module_exit(hello_exit);
Key fixes explained:
- All
MODULE_*macros were missing trailing semicolons — C requires every statement to end with a semicolon. - Your
hello_exitfunction had invalid parameters (...isn't allowed here) and no body. Kernel module exit functions must take no arguments (void). - You forgot to add
module_init()andmodule_exit()macros, which tell the kernel which functions to run when your module is loaded/unloaded.
Step 2: Set Up a Makefile for Kernel Module Compilation
You can't compile kernel modules with plain gcc — you need to use the kernel's build system. Create a file named Makefile in the same directory as kernel_hello.c with this content:
obj-m += kernel_hello.o KDIR := /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) all: $(MAKE) -C $(KDIR) M=$(PWD) modules clean: $(MAKE) -C $(KDIR) M=$(PWD) clean
Step 3: Compile and Test Your Module
- Run the compilation command in your terminal:
This will generate amakekernel_hello.kofile (the compiled kernel module). - Load the module into the kernel:
sudo insmod kernel_hello.ko - Check the kernel log to see your
hello_initmessage:dmesg | tail - Unload the module to trigger the exit function:
sudo rmmod kernel_hello - Check the log again to confirm the exit message appears:
dmesg | tail
内容的提问来源于stack exchange,提问作者user9692088
相关产品推荐
相关产品推荐

