UnsatisfiedLinkErrors with a jar file, JNI and C++

I’ve been busy porting legacy C code to C++. Yeah, real fun. I also have a java gui which calls the C code using the Java Native Interface (JNI). This layer also had to be updated in order to use the C++ code. Everything worked great on windows. I then had to make sure everything built and ran correctly on linux and solaris. I am just not a linux or solaris person. Never have been, never will be. However, I did discover something useful.
I built my jar file and shared objects relatively easily. Next I tried running the jar file. The jar file linked to my shared object ok, but it couldn’t find the function being called. I kept getting an UnsatisfiedLinkError. I guessed the reason was due to C++ name mangling.
Javah is used to create the jni header files. When the header files are created, javah automatically adds:

#ifdef __cplusplus
extern “C” {
#endif

to prevent C++ from mangling function names. I believe the command I used to look at the function names in the shared object was nm. Weird thing is, the names kind of looked mangled. I did some research on the internet, but found nothing useful. Everything worked fine on Windows, the header files use #ifdef cplusplus to prevent name mangling, so how could the function names be mangled? I don’t know. I was desperate, so took the #ifdef cplusplus and put it in the C++ source file too. Right at the top, after the includes and before the first function. I ended the #ifdef cplusplus at the very end of the file. I recompiled and tried running the jar file again. What do you know? No more UnsatisfiedLinkErrors. The jar file found the functions in the shared object just fine. Thank goodness.

Help Them Surf The Web Faster? Make Money Along! Its Too Easy, Try It Now!