Compile Linux Kernel Modules

我正在学习写linux device driver for embedded system.

我有一个linux嵌入式设备,也有这个设备的linux源代码。也有cross compiler tool chain.

第一步,就是写一个简单的hello模块,然后装到设备中。以验证我这个开发环境。

在网上搜索了一下, how to cross compile linux device driver

发现在linux代码根目录的Makefile中有关于cross compile的描述

# Cross compiling and selecting different set of gcc/bin-utils
# ---------------------------------------------------------------------------
#
# When performing cross compilation for other architectures ARCH shall be set
# to the target architecture. (See arch/* for the possibilities).
# ARCH can be set during invocation of make:
# make ARCH=ia64
# Another way is to have ARCH set in the environment.
# The default ARCH is the host where make is executed.

# CROSS_COMPILE specify the prefix used for all executables used
# during compilation. Only gcc and related bin-utils executables
# are prefixed with $(CROSS_COMPILE).
# CROSS_COMPILE can be set on the command line
# make CROSS_COMPILE=ia64-linux-
# Alternatively CROSS_COMPILE can be set in the environment.
# Default value for CROSS_COMPILE is not to prefix executables
# Note: Some architectures assign CROSS_COMPILE in their arch/*/Makefile

 

只要指定ARCH和CROSS_COMPILE就可以了。

在我的这个Makefile中,已经指定了ARCH=arm,CROSS_COMPILE=arm-linux-

 

因为在编译module的时候,使用的是内核构造系统,也就是使用的上面所说的这个在内核源码根目录的Makefile。所以我就不需要在我调用make的命令行中指定ARCH和CROSS_COMPILE了。

 

用来测试的hello模块的源码来自 http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

hello.c

#include <linux/module.h>       /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
#include <linux/init.h> /* Needed for the macros */

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_end(void)
{
printk(KERN_INFO "Goodbye Mr./n");
}

module_init(hello_start);
module_exit(hello_end);

 

Makefile文件是这样的

obj-m = hello.o
KVERSION = 2.6.21
KSRCDIR = /home/seanwu/q2008d/tmq_kernel_2.6.21
all:
    make -C $(KSRCDIR) M=$(PWD) modules
clean:
    make -C $(KSRCDIR) M=$(PWD) clean

 

这个Makefile同样是参考了上面那个网站的文章,但根据我的实际情况做了些调整

KVERSION=2.6.21

是因为在我的设备啥运行uname -r的输出是2.6.21

KSRCDIR指的是我的嵌入式设备的Linux源码所在的位置。

 

然后这个Makefile 和 前面的 hello.c放在一个目录下面。到这个目录下执行make。即可生成hello.ko

 

接下来的步骤是到设备上去加载这个module了。

在设备上运行

mkdir -p /lib/modules/$(uname -r)/kernel/drivers/hello

cp hello.ko /lib/modules/$(uname -r)/kernel/drivers/hello/

然后

insmod hello.ko

即可加载hello模块。

可以看到hello.c中打印出的信息。证明模块已经在设备上转载成功了。

也可以执行

tail -f /var/log/message

查看系统日志。

 

根据上面提到的那篇参考文章,还可以设定模块在系统启动时自动加载。具体这里就不复制了。可以去看那篇文章。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值