1.概要
1.在x86系统上写运行在arm上的驱动
2.代码
1.代码
#include <linux/module.h>
#include <linux/kernel.h>
static int __init helloworld_init(void) //驱动入口函数
{
printk(KERN_EMERG "helloworld_init\r\n");//注意:内核打印用 printk 而不是 printf
return 0;
}
static void __exit helloworld_exit(void) //驱动出口函数
{
printk(KERN_EMERG "helloworld_exit\r\n");
}
module_init(helloworld_init); //注册入口函数
module_exit(helloworld_exit); //注册出口函数
MODULE_LICENSE("GPL v2"); //同意 GPL 开源协议
MODULE_AUTHOR("topeet"); //作者信息
2. makefile
export ARCH=arm64
export CROSS_COMPILE=aarch64-none-linux-gnu- obj-m += helloworld.o #helloworld.c 对应.o 文件的名称。名称要保持一致。
KDIR :=/home/topeet/Linux/linux_sdk/kernel #内核源码所在虚拟机 ubuntu 的实际路径
PWD ?= $(shell pwd)
all:
make -C $(KDIR) M=$(PWD) modules #make 操作
clean:
make -C $(KDIR) M=$(PWD) clean #make clean 操作
代码解释如下:
第
1
行设置
ARCH
变量为
arm64
第
2
行设置交叉编译器前缀为
aarch64-none-linux-gnu-
第
3
行
obj-m += <
文件
>
:将指定的文件(需要是以
.o
结尾)设为编译时以模块形式编译
第
4
行是设备树内核的源码路径,请大家根据实际内核路径进行修改。
第
5
行是获取当前目录的变量
第
7
行是编译
make
操作,会进入内核源码的路径,然后把当前路径下的代码编译成模块。
第
9
行是清除编译文件
3.编译
make
4.模块加载与卸载
1.安装
insmod helloworld.ko
2.卸载
rmmod helloworld
3.查看模块信息
modinfo helloworld.ko
3.运行结果
4.环境准备
1.交叉编译器
1.下载
gcc-arm-10.3-2021.07-x86_64-aarch64-none-linux-gnu.tar.gz
2.解压
sudo tar -vxf gcc-arm-10.3-2021.07-x86_64-aarch64-none-linux-gnu.tar.gz
3.配置
在终端输入“
sudo vi /etc/profile
”命令,在文件最后输入以下命令修改环境变量。
export PATH=$PATH:/usr/local/gcc-arm-10.3-2021.07-x86_64-aarch64-none-linux-gnu/bin
保存退出,在终端输入“reboot”命令重新启动 Ubuntu 系统,使交叉编译环境生效。
4.验证配置是否成功
aarch64-none-linux-gnu-gcc -v