Today I am going to discuss “How to work with Java, JNI and C/C++ libs from command line”.
Actually when you compile and generate .so file for your native code (c/c++) via NDK and try to load this library in Java by calling System.loadLibrary() method, then you will encounter most famous exception UnsatisfiedLinkError .
The same .so file (generated by NDK) work well in Android Application.
This behavior shows that .so file generated by NDK is compatible for Android and normally it is not work well with Core Java code. That's why Today i am going to discuss step by step approach for working with Native code, JNI and core Java.
Step 1 Create folder and necessary file
I am using Linux machine (Ubuntu) for my development, so I am going to create a jniAPP folder under u directory of my machine. In that folder I will keep following file
- .java file (Java class)
- .h file (JNI header file)
- .c or .cpp file (Native code)
- .class file(generated file for java class)
- .so file (generated native shared library)
Use javac command to compile java and javah to generate JNI header file. As for example
/u/jniApp/$ javac HelloJNI.java
/u/jniApp/$ javah HelloJNI
Step 3 compile library
Brief detail of gcc option used above
- -l used to link other shared libraries for current compilation
- -fPIC is a gcc option for creating a position-independent code shared library, so that the shared library can readily be loaded at (more or less) any address in memory.
- -o is option to specify the output file name for the executable
If you don't want to give library(.so) path in java command line like above, in that case you have to modify load library java code as below
you can download whole project from above download link.