Compiling C++ code for JNI binding on Windows with MinGW


Yesterday I spent a good part of my day trying to use the JNI bridge. I was trying to build a very simple spike (basically a HelloWorld example) and call that code from Java. After the usual process of generating headers and including it in C++ code, I run my java code just to get the following exception;


Exception in thread "main" java.lang.UnsatisfiedLinkError: jnidemojava.Main.nativePrint()V
at jnidemojava.Main.nativePrint(Native Method)
at jnidemojava.Main.main(Main.java:27)

After searching for long hours, inspecting the compiled DLL using Anywhere PE Viewer, etc. I found out that that GCC compiler exports function names in shared libraries with a suffix indicating the number of bytes required to hold the arguments passed to the function which is known as name mangling. Therefore, the JNI bridge cannot locate the necessary method! In order to fix this,

-Wall -D_JNI_IMPLEMENTATION_ -Wl,--kill-at

should be added to compiler options during compilation of the DLL. This is explained on the MinGW frequently asked questions.

Thanks to the folks on the Java forums. Here is the link I found out about this information. There are other posible reasons causing you trouble so I’m including the link here which discusses other possible solutions.

BTW, my setup is:

Win XP + MinGW 5.1.4 + MSYS 1.0 + Netbeans 6.1 + Sun JDK 6

9 thoughts on “Compiling C++ code for JNI binding on Windows with MinGW

  1. Hi

    great job.

    Thank you so much.

    I was struggling , what to do. your above information helped me so much.

    Thanks
    Nanaji

  2. Had the same problem and was almost about to lose hope when I saw this post! 🙂 Your info has solved my problem. Thank you! 🙂

    CB

    1. Hi Alan,

      Sorry for the very late reply. I haven’t checked it lately so unfortunately can’t help you.

      Good luck.

  3. thank u very much..
    wasted abt an hour …
    wish i visited ur forum earlier…
    now destination looks near…

Leave a comment