如何在Android中编译驱动模块 .ko

2022-07-28,,,,

简介

调试驱动比较简单快捷的方式,是将驱动程序编译模块,方便快速迭代修改/debug,但是编译如果每次都要make bootimages, 会非常影响开发速度,所以需要有一个相对快捷的方法来直接编译出模块。

Linux方式

Makefile文件写法

obj-m = spi_mcu.o

KDIR := /lib/modules/`uname -r`/build

PWD := $(shell pwd)

all:
	$(MAKE) -C $(KDIR) M=$(PWD) modules

install:all
	$(MAKE) -C $(KDIR) M=$(PWD) modules_install

clean:
	$(MAKE) -C $(KDIR) M=$(PWD) clean

C文件写法

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

static int spi_mcu_init(void)
{
    return 0;
}

static void spi_mcu_exit(void)
{
}

module_init(spi_mcu_init);
module_exit(spi_mcu_exit);

命令行直接make

$ make
make -C /lib/modules/`uname -r`/build M=spi_mcu modules
make[1]: Entering directory `/usr/src/linux-headers-4.4.0-142-generic'
  Building modules, stage 2.
  MODPOST 1 modules
make[1]: Leaving directory `/usr/src/linux-headers-4.4.0-142-generic'
$ file spi_mcu.ko 
spi_mcu.ko: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), BuildID[sha1]=d9a1f37ba99e329384a87b9cb699ed8c1388cc7e, not stripped

生成的是一个X86-64的驱动,适合在pc上安装,不是在Android/ARM设备上安装,下面我们看下arm的方式。

Android方式

obj-m = spi_mcu.o

KDIR := ${OUT}/obj/KERNEL_OBJ/

PWD := $(shell pwd)

all:
	$(MAKE) -C $(KDIR) M=$(PWD) ARCH=arm64 $(KDIR).config modules

install:all
	$(MAKE) -C $(KDIR) M=$(PWD) modules_install

clean:
	$(MAKE) -C $(KDIR) M=$(PWD) clean

将Makefile稍加修改即可,编译得到64位的驱动模块

$ file spi_mcu.ko 
spi_mcu.ko: ELF 64-bit LSB relocatable, ARM aarch64, version 1 (SYSV), BuildID[sha1]=26d68644cfba0bcf91b3af970c8b7b11c4048029, not stripped

问题

编译提示以下问题,google准备弃用GPL的gcc,采用BSD授权的clang/LLVM,要试一下编译的ko是否可以正常工作。

Android GCC has been deprecated in favor of Clang, and will be removed from
Android in 2020-01 as per the deprecation plan in:
https://android.googlesource.com/platform/prebuilts/clang/host/linux-x86/+/master/GCC_4_9_DEPRECATION.md

本文地址:https://blog.csdn.net/weixin_40437029/article/details/109390797

《如何在Android中编译驱动模块 .ko.doc》

下载本文的Word格式文档,以方便收藏与打印。