Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting this UnsatisfiedLinkError with native code?

Tags:

java

native

I have a library called HelloWorld.so and a program HelloWorld.java with this content:

class HelloWorld {
     private native void print();
     public static void main(String[] args) {
         new HelloWorld().print();
     }
     static {
         System.loadLibrary("HelloWorld");
     }
 }

Now when I try to run HelloWorld.java I get this error:

$ /usr/java1.4/bin/java HelloWorld
Exception in thread "main"
java.lang.UnsatisfiedLinkError: no HelloWorld in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1491)
        at java.lang.Runtime.loadLibrary0(Runtime.java:788)
        at java.lang.System.loadLibrary(System.java:834)
        at HelloWorld.<clinit>(HelloWorld.java:7)

Any tips?

like image 871
KNewton Avatar asked Apr 17 '09 18:04

KNewton


1 Answers

I had this problem and fixed it by renaming my library to libHelloWorld.so and following Michael Myers's suggestion. I'm on Arch Linux 64-bit.

HelloWorld.c:

#include <jni.h>
#include <stdio.h>
#include "HelloWorld.h"

/* shamelessly stolen from the book 'The Java Native Interface: Programmer's
   Guide and Specification' */
JNIEXPORT void JNICALL
Java_HelloWorld_print (JNIEnv *env, jobject obj) {
    printf("Hello World!\n");
}

HelloWorld.java:

class HelloWorld {
     private native void print();
     public static void main(String[] args) {
         new HelloWorld().print();
     }
     static {
         System.loadLibrary("HelloWorld");
     }
 }

Building and testing:

$ javac HelloWorld.java
$ javah -classpath . HelloWorld
$ gcc -shared -fPIC -I $JAVA_HOME/include -I $JAVA_HOME/include/linux HelloWorld.c -o libHelloWorld.so
$ java -classpath . -Djava.library.path=. HelloWorld
Hello World!

tl;dr: put lib at the beginning of the library's filename

like image 141
Austin Adams Avatar answered Nov 09 '22 11:11

Austin Adams