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

来源:互联网 发布:淘宝首页导航条代码 编辑:程序博客网 时间:2024/05/01 03:16

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


1. 安装NDK;

2. 编写hello.c源文件

#include <stdio.h>


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


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

4. 运行编译脚本:

chmod u+x compile.sh

./compile.sh hello hello.c


5. 到android设备上运行

adb push hello /data/local/tmp/hello

adb shell /data/local/tmp/hello


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 运行

原创粉丝点击