小工具知识网

当前位置: 首页 > 行业知识 > 【NDK系列】使用ndk-build构建可在Android设备运行的ELF可执行文件

行业知识

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

2026-11-01 22:41:48 来源:互联网转载

背景

通常在安卓开发��程中涉及到的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 := helloworldLOCAL_SRC_FILES := main.cppinclude $(BUILD_EXECUTABLE)

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

main.cpp内容如下:

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

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

cd exec_demondk-build

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

cd libs/arm64-v8afile 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目录下:

adb push ./helloworld data/local/tmp

授予文件可执行权限:

adb shell cd data/local/tmpchmod +x ./helloworld

执行文件查看日志:

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

参考资料

  • NDK Samples: Overview
  • NDK ndk-build Guides
  • ndk编译可执行文件教程

上一篇:基于springboot的酒店客房管理系统----数据库课程设计

下一篇:网易怎么进别的服务器?