在Android系统上运行C/C++程序

1. 安装NDK; linux

2. 编写hello.c源文件 android

#include <stdio.h>


int main() {
        printf("hello, arm c world!\n");
        
        return 0;
} shell


3. 编写编译脚本compile.sh:

#!/bin/bash
PREFIX=$NDK_HOME
CC="$PREFIX/toolchains/arm-linux-androideabi-4.4.3/prebuilt/darwin-x86/bin/arm-linux-androideabi-gcc"
NDK="$PREFIX/platforms/android-14/arch-arm"
CFLAGS="-I$NDK/usr/include"
LDFLAGS="-nostdlib -Wl,-rpath-link=$NDK/usr/lib -L$NDK/usr/lib $NDK/usr/lib/crtbegin_dynamic.o -lc"
$CC -o $1 $2 $CFLAGS $LDFLAGS bash

4. 运行编译脚本: ide

chmod u+x compile.sh ui

./compile.sh hello hello.c idea


5. 到android设备上运行 spa

adb push hello /data/local/tmp/hello orm

adb shell /data/local/tmp/hello io


6. 看到输出结果:

hello, arm c world!

7. 固然,能够直接使用ndk-build命令来编译

a. 新建目录 workspace;

b. 进入workspace,新建目录jni;

c. 进入jni,新建hello.c文件,输入源文件内容;

d. 新建Android.mk文件,内容以下:

LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_SRC_FILES:= hello.c
LOCAL_MODULE := libtest

include $(BUILD_EXECUTABLE)

e. 运行ndk-build命令,可看到在workspace目录下生成了libs和obj两个目录,libs下对应的armeabi文件夹下有生成的可执行文件 test

f. adb push test /data/local/tmp/test

   adb shell test /data/local/tmp/test 运行

相关文章
相关标签/搜索