Richard S
Richard S

Reputation: 11

Compiling JNI C++ Native Code with x86_64-w64-mingw32-g++

I want to compile and run a simple Hello World program that declares and calls a native print method (defined in C++) from Java.

HelloCPP.java

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

HelloCPP.cpp

#include <jni.h>
#include<iostream>
#include "HelloCPP.h" 
using namespace std;

extern "C" 
JNIEXPORT void JNICALL Java_HelloCPP_print(JNIEnv *env, jobject obj){
    cout << "Hello World from C++!" << endl;
    return; 
}

In the command prompt I run the following:

Then the infamous DLL linking/loading error

Exception in thread "main" java.lang.UnsatisfiedLinkError:<"MyProjectDirectory">\HelloCPP.dll: Can't find dependent libraries at java.lang.ClassLoader$NativeLibrary.load(Native Method) at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1941) at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1857) at java.lang.Runtime.loadLibrary0(Runtime.java:870) at java.lang.System.loadLibrary(System.java:1122) at HelloCPP.(HelloCPP.java:8)

Attempted Solutions

Additional Notes

Upvotes: 1

Views: 2336

Answers (1)

Praveena Reddy
Praveena Reddy

Reputation: 41

Java Code: helloworld.java

class helloworld{
    public native void hello();

    static {
            System.loadLibrary("hello");
    }
    public static void main(String args[]){
            new Helloworld().hello();
    }
}

cpp code: hello.cpp

#include<iostream>
#include "helloworld.h"
using namespace std;
JNIEXPORT void JNICALL Java_helloworld_hello(JNIEnv *env, jobject obj)
{
    cout<<"Hello World";

    return;
}

Commands

javac -h . helloworld.java
g++ -I /usr/lib/jvm/java-8-oracle/include/ -I /usr/lib/jvm/java-8-oracle/include/linux/ hello.cpp -shared -o libhello.so -fPIC
java -Djava.library.path=. helloworld

Upvotes: 1

Related Questions