编译内核模块示例

编译内核的时候有两种方式,1:直接编译进内核 2:编译成单独的内核模块insmod。 在这里介绍下单独的内核模块的编译方式,以hello.c进行示范
废话不多说,直接上程序

  1. hello.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

static int __init hello_init(void)
{
	printk(KERN_ALERT "hello driver init \n");
	return 0;
}

static void __exit hello_exit(void)
{
	printk(KERN_ALERT "hello driver exit \n");
}

module_init(hello_init);
module_exit(hello_exit);
  1. Makefile
PWD=$(shell pwd)
KDIR:=/root/exe/firefly/firefly-rk3288-kernel
obj-m:= hello.o

all:
	make ARCH=arm CROSS_COMPILE=/root/exe/firefly/prebuilts/gcc/linux-x86/arm/arm-eabi-4.6/bin/arm-eabi- -C $(KDIR) M=$(PWD) modules

编译完后将编译生成的hello.ko拷贝到开发板上insmod hello.ko执行即可。
注意:CROSS_COMPILE设置需要按照自己的交叉编译链路径设置,KDIR是内核的路径,照抄是不行的

楼主写的不错啊

大神好,同样的代码在ubuntu14.04上编译出错。
hello.c

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

static int __init hello_init(void)
{
        printk(KERN_ALERT "hello driver init \n");
        return 0;
}

static void __exit hello_exit(void)
{
        printk(KERN_ALERT "hello driver exit \n");
}

module_init(hello_init);
module_exit(hello_exit);

Makefile

PWD=$(shell pwd)
obj-m := hello.o
KDIR :=/home/bingo/firefly-rk3288-kernel
default:
	make ARCH=arm  CROSS_COMPILE=/home/bingo/Downloads/arm-eabi-4.6/bin/arm-eabi- -C $(KDIR) M=$(PWD) modules
clean:
	rm -rf *.o *.ko *.mod.c .*.cmd *.markers *.order *.symvers .tmp_versions 

报错

make ARCH=arm  CROSS_COMPILE=/home/bingo/Downloads/arm-eabi-4.6/bin/arm-eabi- -C /home/bingo/firefly-rk3288-kernel M=/home/bingo/Desktop/hello modules
make[1]: Entering directory `/home/bingo/firefly-rk3288-kernel'

  WARNING: Symbol version dump /home/bingo/firefly-rk3288-kernel/Module.symvers
           is missing; modules will have no dependencies and modversions.

  CC [M]  /home/bingo/Desktop/hello/hello.o
In file included from include/linux/mmzone.h:18:0,
                 from include/linux/gfp.h:4,
                 from include/linux/kmod.h:22,
                 from include/linux/module.h:13,
                 from /home/bingo/Desktop/hello/hello.c:2:
include/linux/page-flags-layout.h:5:30: fatal error: generated/bounds.h: No such file or directory
compilation terminated.
make[2]: *** [/home/bingo/Desktop/hello/hello.o] Error 1
make[1]: *** [_module_/home/bingo/Desktop/hello] Error 2
make[1]: Leaving directory `/home/bingo/firefly-rk3288-kernel'
make: *** [default] Error 2

求指点~

bingo 发表于 2018-2-27 10:02
大神好,同样的代码在ubuntu14.04上编译出错。
hello.c

你的错误提示已经出来了,如下所示:
include/linux/page-flags-layout.h:5:30: fatal error: generated/bounds.h: No such file or directory
我在百度上找到了如下的答案,希望可以帮到你
http://blog.chinaunix.net/uid-24919665-id-1630140.html

bingo 发表于 2018-2-27 10:02
大神好,同样的代码在ubuntu14.04上编译出错。
hello.c

你的错误提示已经出来了,如下所示:
include/linux/page-flags-layout.h:5:30: fatal error: generated/bounds.h: No such file or directory
我在百度上找到了如下的答案,希望可以帮到
http://blog.chinaunix.net/uid-24919665-id-1630140.html