Linux下编译构建成功HelloWorld驱动程序并加载
生活随笔
收集整理的這篇文章主要介紹了
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一下;出現下圖錯誤;下回再整;
總結
以上是生活随笔為你收集整理的Linux下编译构建成功HelloWorld驱动程序并加载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux insmod 命令学习
- 下一篇: CentOS源码下载和Windows平台