Search code examples
javac++linuxjava-native-interfaceunsatisfiedlinkerror

Linux, java.lang.UnsatisfiedLinkError: no "library file" in java.library.path


I'm trying to run a simple JNI example where I run a java application that calls a c++ function through a dynamic library.

I'll post the following codes and terminal commands that I used.

.java

public class Lab{
   public native void hello();

   static {
      System.loadLibrary("hello");
   }

   public static void main(String args[]) {
      new Lab().hello();
   }
}

get .class and header file through terminal

javac Lab.java
javah -jni Lab

hello.cpp file

#include "Lab.h"
#include <stdio.h>
#include <iostream>

JNIEXPORT void JNICALL Java_Lab_hello(JNIEnv *env,jobject jobj) {
   cout<<"Hello World"<<endl;
}

Generating the lib file "hello.so":

gcc -shared -fpic -o hello.so -I/usr/lib/jvm/jdk1.8.0_45/include -I/usr/lib/jvm/jdk1.8.0_45/include/linux hello.cpp

and finally run the file:

java -Djava.library.path=. Lab

and then I get the error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no hello in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1865)
        at java.lang.Runtime.loadLibrary0(Runtime.java:870)
        at java.lang.System.loadLibrary(System.java:1122)
        at Lab.<clinit>(Lab.java:6)

I know that there is other posts with this same issue but none of those solutions worked for me, unfortunately. I already tried things such as:

  • copy the hello.so file into "/usr/lib" which is in the java lib path and give it permissions with chmod;
  • add the hello.so file path to $LD_LIBRARY_PATH using export aswell;
  • add hello.so path when running the java file (java -Djava.library.path="/root/Desktop" Lab);
  • use ldconfig which didn't even work.

I need to use this on a major application but I was just trying a quick example and I couldn't make it work even with all the solutions I read on other posts.

Thank you.


Solution

  • Another day of searching through Stack and found what I needed here. On Linux the .so lib files must have the prefix "lib". So on my example my lib file should be named libhello.so instead of hello.so and everything works.