Linux下编译构建成功HelloWorld驱动程序并加载

编写一个hello_world.c的驱动程序;

hello_world.c;

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

//指定license版本
MODULE_LICENSE("GPL");              

//设置初始化入口函数
static int __init hello_world_init(void)
{
    printk(KERN_DEBUG "hello world!!!\n");
    return 0;
}

//设置出口函数
static void __exit hello_world_exit(void)
{
    printk(KERN_DEBUG "goodbye world!!!\n");
}

//将上述定义的init()和exit()函数定义为模块入口/出口函数
module_init(hello_world_init);
module_exit(hello_world_exit);

写一个makefile; 

obj-m+=hello_world.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

执行make命令;没有make命令;执行 sudo apt install make,来安装make命令;

再执行make;提示下图错误;

把makefile文件中的提示出错行的空格改为Tab键盘;

再执行make命令;提示没有Makefile文件;

    把makefile改为Makefile;此文件没有后缀名;

然后再make;gcc没有安装,

安装gcc;

构建驱动程序成功;如下图;hello_world.ko出来了,这个是构建好的驱动程序;

执行insmod,加载,

加载成功;用lsmod列出模块看一下,hello_world驱动已经被加载;

下面看一下写一个测试程序来测试一下驱动;test.c;

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int fd;
    int val = 1;
    
    fd = open("hello_world", O_RDWR);
    if(fd == -1)
    {
        printf("can't open...\n");
        exit(EXIT_FAILURE);
    }
    
    read(fd, &val, sizeof(val));
    
    exit(EXIT_SUCCESS);
}

gcc一下;出现下图错误;下回再整;

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值