Tips & Tricks on Android

Friday, February 20, 2009

Hello World in C on Android

If you've been following the Android world, you'd know that Android's SDK requires you to write apps in Java. Ever since I got my phone I've been dying to run a Hello World C program, but I've been unable to get the right cross compiler for it.

Today I finally managed to do it using CodeSourcery's cross compiler on linux. A cross compiler is something which allows you to compile on one architecture (the host) and run the executable binary on another (the target). In this case, the host is the linux machine where we'll install the toolchain (linux intel x86) and android phone is the host (arm).
  1. Download CodeSourcery's toolchain installer for GNU/Linux target for IA32 host
  2. Install it: sh arm-2008q3-72-arm-none-linux-gnueabi.bin
  3. The toolchain provides the cross compiler arm-none-linux-gnueabi-gcc. You need to put it's directory in your $PATH. Once you have the toolchain, you can easily compile your hello world program: arm-none-linux-gnueabi-gcc -o hello -static hello.c
  4. Copy the binary to your phone and run it from an adb shell prompt: ./hello
Voila!

Points to note:
  • The above binary is static, that is it does not use the phone's libc libraries. Android ships with its own trimmed down version of libc, called bionic. Next I'll be trying to compile and run using bionic libc, so that I don't have to compile statically
  • The above steps do not use the toolchain in the android source code. I'll try later to cross compile using that.