Straightforward Android Native Executables

I spent some time trying to figure out how to build a native code "Hello, world!" program for Android and noticed that prior to the r4b release of the Android NDK, there is a lot of bad info out there on how to do this. Usually, it involves using some kind of unofficial cross-compiler, plus the entire source tree of the Android OS, and/or whatever other kludgy hacks like linking the executable statically to some kind of ARM libc. This seems bad. With the newest version of the NDK generating a proper gdbserver executable and gdb setup stubs, why anyone would want to do this by hand is beyond me.

There was a script that made sense at one point: agcc.pl (here), which essentially takes all of the Makefile fragments and command-line switches and wraps them for you, letting you treat the NDK's cross-compilers almost like a normal gcc, but this is probably still more work than it's worth.

The Easy Way

The easiest way to get the NDK to build a native executable for you is just to use

include $(BUILD_EXECUTABLE)

at the end of your Android.mk, and then build like normal.

Anything else will just cause premature baldness.

Read on to see a fully-worked example...\

hello-exe.c

#include
int main(int argc, char ** argv)
{
	printf("Hello, world!n");
	return 0;
}

Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := hello-exe
LOCAL_SRC_FILES := hello-exe.c

include $(BUILD_EXECUTABLE)

Example build + install output (it really is that easy)

vilimpoc@funky ~
$ cd ~/android-ndk-r4b/samples/hello-exe

vilimpoc@funky ~/android-ndk-r4b/samples/hello-exe
$ ls
jni

vilimpoc@funky ~/android-ndk-r4b/samples/hello-exe
$ ~/android-ndk-r4b/ndk-build -B
Compile thumb  : hello-exe <= /home/vilimpoc/android-ndk-r4b/samples/hello-exe/jni/hello-exe.c
Executable     : hello-exe
Install        : hello-exe => /home/vilimpoc/android-ndk-r4b/samples/hello-exe/libs/armeabi

vilimpoc@funky ~/android-ndk-r4b/samples/hello-exe
$ ls
jni  libs  obj

vilimpoc@funky ~/android-ndk-r4b/samples/hello-exe
$ cd libs/armeabi

vilimpoc@funky ~/android-ndk-r4b/samples/hello-exe/libs/armeabi
$ ls
hello-exe

vilimpoc@funky ~/android-ndk-r4b/samples/hello-exe/libs/armeabi
$ adb devices
List of devices attached
emulator-5554   device

vilimpoc@funky ~/android-ndk-r4b/samples/hello-exe/libs/armeabi
$ adb -e shell
# mkdir /data/data/hello-exe
# ls /data/data/hello-exe
# exit

vilimpoc@funky ~/android-ndk-r4b/samples/hello-exe/libs/armeabi
$ adb -e push hello-exe /data/data/hello-exe/hello-exe
427 KB/s (0 bytes in 13670.000s)

vilimpoc@funky ~/android-ndk-r4b/samples/hello-exe/libs/armeabi
$ adb -e shell
# cd /data/data/hello-exe
# ls -l
-rw-rw-rw- root     root        13670 2010-09-23 12:37 hello-exe
# chmod 777 ./hello-exe
# ls -l
-rwxrwxrwx root     root        13670 2010-09-23 12:37 hello-exe
# ./hello-exe
Hello, world!
#
# exit

vilimpoc@funky ~/android-ndk-r4b/samples/hello-exe/libs/armeabi
$