Build linux kernel Module

原文连接:http://www.cyberciti.biz/tips/build-linux-kernel-module-against-installed-kernel-source-tree.html

一 在没有linux kernel源码的条件下build linux kernel module

How do I build Linux kernel module against installed or running Linux kernel? Do I need to install new kernel source tree from kernel.org?

坦白的说,你并需要一个新的linux kernel source tree(dowload from kernel.org).也就是说,build kernel driver或module并不要求你下载一个展开的linux kernel源码树结构。

二 linux kernel header

如果你要构建新的linux kernel driver或module, linux kernel header是必须的。

假设当前你的系统是debian 5 lenny。

更新你的aptitude的列表:

aptitude update

查询linux kernel header deb package.

aptitude search linux-headers-$(uname -r)

安装linux-header-* package

apt-get install linux-headers-$(uname -r)

查询当前的kernel build directory

ls –d /lib/modules/$(uanem -r)/build

创建你开发的新的module的目录:

mkdir ~/test

cd ~/test

vi 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
hello.c内容

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

static int __init
hello_start(void)
{
  printk(KERN_INFO "loading hello module.../n");
  printk(KERN_INFO "hello world/n");
  return 0;
}

static void __exit
hello_exit(void)
{
  printk(KERN_INFO "Goodbye Yubo./n");
}

module_init(hello_start);
module_exit(hello_exit);

 
然后,在~/test 目录下,make
就可以编好hello.ko module
接下来可以使用lsmod, insmod, rmmod, modinfo 来对hello module进行操作。
lsmod | grep hello
insmod hello.ko
rmmod hello
modinfo hello 查看module hello 的信息
 
在系统启动的时候加载module, 修改/etc/modules, 这个文件的每一行配置一个module的名字,
接下来再mkdir –p /lib/modules/$(uname -r)/kernel/drivers/hello
然后拷贝hello.ko 到/lib/modules/$(uname -r)/kernel/drivers/hello目录下
编辑/etc/modules
添加一行hello
原文地址:https://www.cnblogs.com/yuboyue/p/2109858.html