Linux下编译构建成功HelloWorld驱动程序并加载
生活随笔
收集整理的這篇文章主要介紹了
Linux下编译构建成功HelloWorld驱动程序并加载
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
編寫一個(gè)hello_world.c的驅(qū)動(dòng)程序;
hello_world.c;
#include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> //指定license版本 MODULE_LICENSE("GPL"); //設(shè)置初始化入口函數(shù) static int __init hello_world_init(void) {printk(KERN_DEBUG "hello world!!!\n");return 0; }//設(shè)置出口函數(shù) static void __exit hello_world_exit(void) {printk(KERN_DEBUG "goodbye world!!!\n"); }//將上述定義的init()和exit()函數(shù)定義為模塊入口/出口函數(shù) module_init(hello_world_init); module_exit(hello_world_exit);寫一個(gè)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執(zhí)行make命令;沒有make命令;執(zhí)行 sudo apt install make,來安裝make命令;
再執(zhí)行make;提示下圖錯(cuò)誤;
把makefile文件中的提示出錯(cuò)行的空格改為Tab鍵盤;
再執(zhí)行make命令;提示沒有Makefile文件;
? ? 把makefile改為Makefile;此文件沒有后綴名;
然后再make;gcc沒有安裝,
安裝gcc;
構(gòu)建驅(qū)動(dòng)程序成功;如下圖;hello_world.ko出來了,這個(gè)是構(gòu)建好的驅(qū)動(dòng)程序;
執(zhí)行insmod,加載,
加載成功;用lsmod列出模塊看一下,hello_world驅(qū)動(dòng)已經(jīng)被加載;
下面看一下寫一個(gè)測試程序來測試一下驅(qū)動(dòng);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一下;出現(xiàn)下圖錯(cuò)誤;下回再整;
總結(jié)
以上是生活随笔為你收集整理的Linux下编译构建成功HelloWorld驱动程序并加载的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux insmod 命令学习
- 下一篇: CentOS源码下载和Windows平台