Sunday, August 15, 2010

Native android C program using ndk

Big update: I updated agcc.pl to work with the latest NDK release, and called it agcc2.pl. Here is the new blog post.

Update: link to agcc.pl works now. Update 2: link to agcc.pl *actually* works now?

The Android NDK isn't really intended to write standalone binaries, but this tutorial got me most of the way there. But some path changes in android-ndk-r4b broke the agcc wrapper, so I had to modify it to point to the right includes and libraries.

Here's what should be a complete HOWTO for linux. It probably requires a rooted phone at the least, in order to upload and run arbitrary binaries. I'm running a pre-release of cyanogenmod CM6.

1. Download and unpack android-sdk_r06-linux_x86.tgz and android-ndk-r4b-linux-x86.zip.

2. Add android-ndk-r4b/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin and android-sdk-linux_86/tools/ to your PATH. (cd into each of those directories and then run "export PATH=$PATH:`pwd`")

3. Plug your phone in via USB and run "sudo adb start-server" to start the daemon in the background (as root so that it can access the USB device. If you accidentally start the daemon as yourself and can't talk to your phone, run "adb kill-server" to kill it, then "sudo adb start-server" to restart it as root.)

4. Make sure you can run "adb" (from the SDK) and "arm-eabi-gcc" (from the NDK) so that you know your PATH is set up right.

5. Grab my copy of the agcc wrapper hacked for android-ndk-r4b. "chmod 755" it so you can run it.

6. Create the "hello, world" .c file:
#include <stdio.h>

int main() {
  printf("Hello, world!\n");
}

7. Ready to compile! "$ agcc.pl -o hello hello.c"

8. Copy the binary to /data: "adb push hello /data/"

9. Run it! I did that by SSHing into the phone, but you can also just "adb shell".
# cd /data
# ./hello
Hello, world!

7 comments:

Linux4all said...

thanks nice tutorial.
but after copying hello in /data using adb push when i execute ./hello i am getting error as hello file not found.

agcc.pl is not able to download

Anonymous said...

Hm, the agcc.pl link works for me. If you click it, you should see a download page for the file. You could also try this link: http://android-cruft.googlecode.com/svn/trunk/ndk/agcc.pl

Did you cd /data before running ./hello? That's the only reason I can think of why you might get "file not found".

Anonymous said...

cannot download agcc.pl please post another copy!

Anonymous said...

Please post another copy of agcc.pl the link provided is dead!

Lunkwill said...

I've updated the link. Let me know if you still have trouble.

Anonymous said...

Cool Post! Worked out of the Box. Thanks a lot. :-)

Anonymous said...

I have the correct PATH set to arm-eaib-gcc. However, when I run agcc.pl I get an bad arm-eaib-gcc path error. Any ideas?