Debian/Ubuntu 搭建写模块(驱动)编程的环境-ZT

来源:互联网 发布:男人学什么乐器好 知乎 编辑:程序博客网 时间:2024/05/16 00:40

之前在Ubuntu里写个kernel module 的 hello world. make出错.
后来知道是因为Ubuntu没有KERNEL 原码树, 以为Ubuntu主打桌面,而且Ubuntu桌面是比较慢.
所以就换用Debian了. 但是Debian 装好后还是没有原码树...
所以在这里记录一下安装的方法:

1. 查看自己系统的内核版本:
hengl@lhdebian:~$ uname -r

2.6.26-1-686

2. 安装相应版本的内核原码包:
hengl@lhdebian:~$ sudo apt-get install linux-source-2.6.26

然后在/usr/src/ 下就会有内核原码包,是一个压缩包.
hengl@lhdebian:~$ ls /usr/src/
linux-source-2.6.26.tar.bz2

3. 解压该包:
hengl@lhdebian:/usr/src$ sudo tar -xvf linux-source-2.6.26

然后会生成内核原码目录: linux-source-2.6.26

4. 配置内核:
hengl@lhdebian:/usr/src/linux-source-2.6.26$ sudo make oldconfig

也可以使用别的配置方式 : menuconfig , xconfig. 看自己的需求了.

5. 编译内核:
hengl@lhdebian:/usr/src/linux-source-2.6.26$ sudo make bzImage

这个操作要花一些时间,然后会在当前目录下www.linuxidc.com生成一个新的文件: vmlinux

6. 编译 模块:
hengl@lhdebian:/usr/src/linux-source-2.6.26$ sudo make modules

这里要花更长一些时间... ...

7.安装 模块:
hengl@lhdebian:/usr/src/linux-source-2.6.26$ sudo make modules_install

然后会在 /lib/modules/ 目录下生成 目录 : 2.6.26. make 模块的时候用到的就是它了.

至此, 就搞了, 重启一下系统, 写个网上到处可以找到的hello world试试:

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

MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void)
{
        printk(KERN_ALERT "Hello,world/n");
        return 0;
}

static void hello_exit(void)
{
        printk(KERN_ALERT "Goodbye cruel world/n");
}

module_init(hello_init);
module_exit(hello_exit);

 

Makefile 内容:

obj-m := hello.o
KERNELDIR := /lib/modules/2.6.26/build
PWD := $(shell pwd)

modules:
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules

modules_install:
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install


然后make 吧, 我的是没问题了.
成功的话会在当前目录生成hello.ko , 它就是要加载上内核里的模块文件了.

8. 加载模块:
hengl@lhdebian:~/code/hello$ sudo insmod hello.ko

模块的输出可以在 /var/log/syslog 文件里查看.

9. 删除模块
hengl@lhdebian:~/code/hello$ sudo rmmod hello

~~~
hello world 运行成功了, 就走出第一步了, 就可以往下走了.


以上内容转自别人的博客。

我自己在用Debian4编写内核模块是发现,其实可以不安装 linux-source-2.6.26 包,只需要安装你现在系统对应的 linux-headers-xxxx (其中xxxx为你用uname -r 得到的版本号 比如 2.6.26-1-686) 就可以。然后在写Makefile的时候这样写(以2.6.26-1-686为例):

obj-m := hello.o
KERNELDIR := /usr/src/linux-headers-2.6.26-1-686
PWD := $(shell pwd)

modules:
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules

modules_install:
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install


就可以了。

原创粉丝点击