Native C applications for Android
作者: 刘鹏
日期: 2009-03-26
本文以经典的 hello 程序为例介绍了在 android 平台上编译和运行 C 程序的步骤。

简介

Android 的 Java SDK 功能丰富,但是若你想运行一些 C 服务或者代码,也并 不困难。你可以使用标准的 Linux cross-compiler 编译应用程序,并从 shell 里运行你的程序。

下面介绍下具体步骤。

下载 cross-compiler

http://www.codesourcery.com/gnu_toolchains/arm/download.html

保证选择的是 ARM GNU/Linux target。

下载完成后会得到一个脚本 arm-2008q3-72-arm-none-linux-gnueabi.bin,先 为其增加可执行属性,然后以 root 身份运行,根据提示安装即可。

hello.c 源码


#include <stdio.h>

int main ()
{
    printf ("Hello, Android.\n");

    return 0;
}


编译并将可执行程序上传到设备

编译源程序:


$ arm-none-linux-gnueabi-gcc -static hello.c -o hello

将可执行文件上传到模拟器:


$ adb push hello/hello data/hello
$ adb shell chmod 777 data/hello

也可先运行 adb shell 进入 shell 中进行操作。

运行程序


$ adb shell data/hello

在 shell 中应该可以看到:

$Hello, Android.

注意

需要进行静态编译,否则会出现"not found"的错误。

See Also

http://benno.id.au/blog/2007/11/13/android-native-apps