Tuesday, May 8, 2012

NDK - Using System Libraries


Building NDK Apps that Uses System Libraries


Many a times we create NDK libs which has code depending on External System Libraries  and which are not available with nominal NDK lib(s)

e.g. libcrypto, libskia,libgui... . To build this kind of apps we essentially need to build the app along with Android Source code
We can build the same in Windows machine

What you need
1. Target Android Platform Source Code
2. Target Android Rooted Device
3. If Building from Windows , Cygwin (not required from ndk release-8)

Steps


1. Include all the header files required by the project in your Target NDK Platform "/usr/include" or any other local folder.  The header files can be obtained from Source code Directory and from other sources.

e.g  To include dsa.h available in openssl , get it from
“\source\external\openssl\include\openssl\” folder and place it in
“\android_ndk\android-ndk-r7\platforms\android-14\arch-arm\usr\include\openssl\” folder or somewhere in your directory structure. In the latter case ensure to include the path in 
your jni project's Android.mk file at


LOCAL_C_INCLUDES := \ 
                   path/to/your/header/files



2. Pull the corresponding/required libraries (".so") file from the Target Android Rooted Device “/system/lib” folder and copy to
  “\android_ndk\android-ndk-r7\platforms\android-14\arch-arm\usr\lib\” folder or copy it on your specified path. 

3. In the Android.mk file of your JNI project refer the library for dynamic linking
   
  e.g for referencing the libcrypto.so available in your ndk's platform /usr/lib folder
  LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib –lcrypto


or to specify a path for dynamic linking of your library files use 


  LOCAL_LDLIBS +=-Lpath/to/your/lib/file/libxyz.so

4. Build as usual in Cygwin/prompt, Ignore the warnings. Resolve errors  if any.

5. You can start static loading the Library from Java code. The app is guaranteed to work in the target devices and depending on   libraries being linked can also work in other devices.

Common Errors:


1. Undefined references 

   -> probably any one of the required libraries has not be linked, link it in  Android.mk file.

   -> Definition of any of function declared might be missed
      in your source files 

2. Re-definitions of function/struct/enums/ in your included files

  -> This will show the include files at which the redefinition happens, comment out the re-definitions in header files intelligently