Search code examples
androidandroid-ndkjava-native-interfacecross-compiling

Cross-compiling a C library for Android NDK


I'm a bit confused with what I'm currently attempting: I want to cross-compile a C library for use with Android through the NDK, so that I can create a JNI wrapper and call some of its functions from my Android java code.

  • I followed this guide to crosscompile libopus (the library I want to include in my project): http://mortoray.com/2012/08/21/android-ndk-cross-compile-setup-libpng-and-freetype/ which means I currently have a standalone toolchain at /opt/android-ext/, with a lib folder that contains the library I cross-compiled (libopus.a, libopus.so, etc).

  • I also already have a jni folder on my Android project, which contains some C code with the JNI bindings that I want, and that I can call from my Java code, but it does nothing (I can call it but it's a blank function). This means that in my project, there's a /lib/armeabi directory with "libopusUtilsNative.so" (the wrapper).

My question is:

How do I add the library that I just crosscompiled to the project, so that (for example) I can just do an #include call on the C source code file that I already have and get access to the library functions? I'm a bit lost with how to:

  1. Include the library I cross-compiled into my project.

  2. How to make the wrapper code I created include it (I'm guessing this has something to do with adding some code to my Android.mk file, but I'm clueless).


Solution

  • The guide that you linked to contains an example of how to modify the Android.mk file for your JNI library (or in his case, a native app) to link against the cross-compiled library:

    PLATFORM_PREFIX := /opt/android-ext/
    
    LOCAL_PATH := $(PLATFORM_PREFIX)/lib
    include $(CLEAR_VARS)
    LOCAL_MODULE := libpng
    LOCAL_SRC_FILES := libpng.a
    include $(PREBUILT_STATIC_LIBRARY)
    
    # The in your project add libpng
    LOCAL_STATIC_LIBRARIES := android_native_app_glue libpng
    

    That's pretty much how you'd do it if you wanted to link statically against libopus. Or if you want to link against the shared library, use something like this: Using my own prebuilt shared library in an Android NDK project