嵌入式Linux2.6 Kernel Module模板动态加载实例和常见问题解决方法

 

/* hello.c */

#include <linux/module.h>       /* Needed by all modules */
#include <linux/init.h>         /* Needed for the module-macros */
 
static int __init hello_init(void)    // Module entry function specified by module_init()
{
        printk("Hello,world!/n");
        return 0;
}
 
static void __exit hello_exit(void)  //Module exit function specified by module_exit()
{
        printk("Goodbye,cruel world!/n");
}
 
module_init(hello_init);
module_exit(hello_exit);
 
MODULE_LICENSE("Dual BSD/GPL");  //should always exist or you’ll get a warning
MODULE_AUTHOR("wfg"); //optional
MODULE_DESCRIPTION("STUDY_MODULE"); //optional
 
/* Makefile */
# Makefile2.6
ifneq ($(KERNELRELEASE),)
#kbuild syntax. dependency relationship of files and target modules are listed here.
obj-m +=hello.o
#obj-m :=gpio_driver.o
else
PWD :=$(shell pwd)
KEVER ?=$(shell uname -r)
#KDIR :=/home/wfg/linux-2.6.26.3/$(KEVER)/build
#KDIR :=/home/wfg/linux-2.6.26.3
KDIR :=/home/wuyan/download/linux-2.6.26
default:
 #$(MAKE) -C $(KDIR) M=$(PWD)
 make -C $(KDIR) M=$(PWD) modules
clean:
 rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions *.order *symvers
endif
 
obj-m := hello.o表示编译后生成hello.o模块。
$(KDIR) 指定了内核源码的路径,“M=”表示这是个外部模块,M=$(PWD) 指定了该模块文件所在的路径。
注: makefile预定义了$(PWD)变量,此处可以不必重复定义。
 
执行#make编译成功后将生成的hello.ko拷贝到nfs文件系统。需要注意的是insmod等模块加载命令需要从lib/modules/2.6.26.6
的目录下加载模块,所以必须先建立此目录,然后将模块放到此目录下面,否则将出现以下两种情况:
一是没有建立lib/modules/2.6.26.6目录,取决于内核版本号,将出现insmod: chdir(2.6.26.6): No such file or directory的错误
二是只将模块简单地放在根目录或其它文件夹,没有将其拷贝到指定的lib/modules/2.6.26.6目录,将出现
insmod: module 'gpio_driver' not found错误
 
 
加载到开发板上运行
#insmod hello.ko
Hello,world!
#lsmod 输出内核已加载模块信息,可以查看到刚刚加载成功的hello模块
……
Module                  Size  Used by
hello                   5632  0
 
卸载模块
#rmmod hello.ko
Goodbye,cruel world!
#lsmod 发现hello模块已经被卸载
 
 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值