【NDK系列】使用ndk-build构建可在Android设备运行的ELF可执行文件

背景

通常在安卓开发过程中涉及到的NDK开发产物都是以JNI+so文件为主的library(库文件),包括谷歌官网给出的示例也是演示了如何开发一个JNI库。本文则是介绍如何利用NDK开发一个最简单的可以在Android设备运行的可执行程序。

开发步骤

创建以下目录结构的项目工程:

复制代码
exec_demo
		├── jni
		   ├── Android.mk
		   └── main.cpp

其中Android.mk中的内容如下:

复制代码
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE := helloworld
LOCAL_SRC_FILES := main.cpp
include $(BUILD_EXECUTABLE)

Android.mk相关代码可以从官网demo获取。

main.cpp内容如下:

cpp 复制代码
#include <jni.h>
#include <stdio.h>

int main(int argc, char const *argv[])
{
    printf("hello world from %d, %s\n", argc, argv[0]);
    return 0;
}

执行编译,生成可执行文件

bash 复制代码
cd exec_demo
ndk-build

编译完成可以在libs/arm64-v8a目录下找到helloworld可执行文件,查看该文件信息如下:

bash 复制代码
cd libs/arm64-v8a
file helloworld

输出结果如下:

复制代码
helloworld: ELF 64-bit LSB pie executable, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /system/bin/linker64, BuildID[sha1]=9046a35e13dc3a13a1de6a0dc8007456de28aa66, stripped

测试效果

先推送可执行文件到/data/local/tmp目录下:

bash 复制代码
adb push ./helloworld data/local/tmp

授予文件可执行权限:

bash 复制代码
adb shell 
cd data/local/tmp
chmod +x ./helloworld

执行文件查看日志:

bash 复制代码
# 无参执行
127|mayfly:/data/local/tmp $ ./helloworld
hello world from 1, ./helloworld
# 输入多个参数
mayfly:/data/local/tmp $ ./helloworld 1 2 3 4
hello world from 5, ./helloworld

参考资料

相关推荐
大熊的瓜地12 分钟前
Android automotive 框架
android·android car
私人珍藏库1 小时前
[Android] Alarm Clock Pro 11.1.0一款经典简约个性的时钟
android·时钟
消失的旧时光-19433 小时前
ScheduledExecutorService
android·java·开发语言
小糖学代码4 小时前
MySQL:14.mysql connect
android·数据库·mysql·adb
怪兽20146 小时前
请谈谈什么是同步屏障?
android·面试
帅锅锅0076 小时前
SeLinux 全面详解
android·linux
只想搞钱的肥仔6 小时前
Android thermal (5)_cooling device(下)
android
某空m7 小时前
【Android】BottomNavigationView实现底部导航栏
android·java
撩得Android一次心动8 小时前
Android 四大组件桥梁 —— Intent (意图) 详解
android
用户2018792831678 小时前
MVP架构模式:餐厅点餐的有趣故事
android