Build Standalone Binaries in C for Android

Procedure is simple. Here is the detailed steps and hopefully it is helpful for others.

Preparation

  • Know your Android system code, whether it's android-18, or android-22, or others. Here we assume android-21.
  • Download the latest NDK. Here we assume NDK path is /home/happyz/ndk (or simply ~/ndk)
  • Figure out the gcc version, either 4.8 or 4.9. If not, update it.
  • Assume the output folder you want to store the toolchain is at ~/androidLib/
  • Our system is Ubuntu 64-bit, therefore we need to specify --system=linux-x86_64

Details

cd ~/ndk/build/tools
./make-standalone-toolchain.sh --toolchain=arm-linux-androideabi-4.9 --platform=android-21 --install-dir=~/androidLib/android-21-toolchain/ --ndk-dir=~/ndk/ --system=linux-x86_64

Then just set PATH to be:

export PATH=$PATH:/home/happyz/androidLib/android-21-toolchain/

And we can just use arm-linux-androideabi-gcc to compile our C code.

Example Makefile

CC = arm-linux-androideabi-gcc
CFLAGS = -pie -fPIE
TARGET = myDemo

OBJS = $(patsubst %.c, %.o, $(wildcard *.c))
HEADERS = $(wildcard *.h)

all: $(TARGET)

%.o: %.c $(HEADERS)
    $(CC) $(CFLAGS) -c $< -o $@

.PRECIOUS: $(TARGET) $(OBJS)

$(TARGET): $(OBJS)
    $(CC) $(OBJS) -Wall $(CFLAGS) -o $@

clean:
    -rm -f *.o
    -rm -f $(TARGET)

Leave a comment

Your email address will not be published. Required fields are marked *