ZiviMagic
ZiviMagic

Reputation: 1054

Gradle using PreBuilt Static Library

I am moving from Eclipse to Android Studio and I am trying to use Gradle in order to include a PreBuilt static library. I am following the two-libs sample provided with the ndk sample projects and implement it in Android Studio.

What I have:

The prebuilt static library:

[ndk-path]\samples\two-libs\obj\local\armeabi-v7a\libtwolib-first.a

The header file for the library:

[ndk-path]\samples\two-libs\jni\first.h

containing a single method:

extern int first(int  x, int  y);

Now how do I use it as a prebuilt static library in android studio?

What I tried:

Adding the files: Added the library to my android studio project by creating jniLibs (I read this is used for preBuild dynamic libraries, not sure if preDuilt static libraries should be using this path as well):

[android-studio-project-path]\app\src\main\jniLibs\armeabi-v7a\libtwolib-first.a

And added the header file to:

[android-studio-project-path]\app\src\main\jni\first.h

Code changes:

In java: called a native method Foo.

In the JNI header file: declared the Foo method.

In the c file implementing the JNI header: added the #include "first.h" and called the first method.

But I get an error during compilation:

"error: undefined reference to 'first'"

Which I am guessing it is because during compile time it doesn't find the implementation file for first.h and does not enable to dynamically load it. If I add the first.c file (the implementation file and not loading it as a library it works)

I am new to c code and JNI, so any help would be nice!

Upvotes: 2

Views: 1406

Answers (1)

TimoM
TimoM

Reputation: 53

I was struggling with the same problem and tried all kinds of tricks wasting quite a bit of time until I bumped into this: https://groups.google.com/d/msg/adt-dev/FoyeXl2vl3s/jLvH5lztDwAJ and found the solution. In your build.gradle file put the prebuilt lib as part of ldLibs in the android.ndk section, e.g.

android.ndk {
    moduleName = "myJniModule"
    stl = "gnustl_shared" // Or whichever you like
    // Put your cppFlags or CFlags here too
    ldLibs += ['twolib-first'] // The name of your prebuilt lib without file suffix and 'lib' prefix
}

Then in productFlavors add path of the prebuilt lib in ldFlags:

android.productFlavors {
    create("arm") {
        ndk.with {
            abiFilters += "armeabi-v7a"
            ndk.ldFlags += "-L${file("app/src/main/jniLibs/armeabi-v7a/")}".toString()
        }
    }
}

This worked for me at least. I'm using the experimental Gradle plugin v0.2.0.

Upvotes: 1

Related Questions