Tuesday, May 12, 2009

How to build and use a shared libraries in Android

Actually, it is very simple to build and use your own shared library,

For the shared library, you need to create an Android.mk like this:

  LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
  LOCAL_SRC_FILES := hello.c
  LOCAL_CFLAGS :=
  LOCAL_C_INCLUDES :=
  LOCAL_SHARED_LIBRARIES := libc        <=== may be not required 
  LOCAL_MODULE := libhello
  include $(BUILD_SHARED_LIBRARY)

For the executable that needs use this shared library, the Android.mk needs to be written as :

  LOCAL_PATH:= $(call my-dir)
  include $(CLEAR_VARS)
  LOCAL_SRC_FILES := main.c
  LOCAL_SHARED_LIBRARIES := libc libhello
  LOCAL_MODULE := myprog          <=== the name of final executable 
  include $(BUILD_EXECUTABLE)


Besides makefile changes, we also need to change build/core/prelink-linux-arm.map. Android does prelink (a modified version), all the memory location of DSO are predefined. In order to build a shared library for Android, you need to define the address and size for the memory used by your DSO (before you start to build anything). For current example, I have added following lines at the end of .map file.

  libhello.so            0x9A100000
  The C code I'm using to build this example is
main.c
  #include "myprog.h"
  int main(void)
{
hello("World!");
return 0;
}


  Hello.c
#include
  void hello(const char* name)
{
printf("Hello %s!\n", name);
}

1 comment: