$ls Hello.class Hello.h Hello.java  ## The C side We now have three files and we can create a C file with the following code: #include <jni.h> #include <stdio.h> #include "Hello.h" JNIEXPORT void JNICALL Java_Hello_sayHello (JNIEnv *env, jobject obj) { printf("Hello world!\n"); return; }  It can be seen that we are passing the same parameters to the method as in the *.h file, but now with names specified. Now, we have to compile our (dynamic) library; thus, we don’t link the program, and just compile it with the appropriate libraries. Depending on your platform, the java SDK might be installed in /usr/share/ or /opt/ (Linux users) or /System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Headers/ (Mac users). $ gcc -c -I/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Headers/ \
-o hello.o Hello.c


If all went file, you should get the file hello.o.

## Assembling the different pieces of code

Now, we just have to create a definition file, ending with *.def. It is used to specify the names of the functions that are to be exported, or in other words the visible functions. It looks like

EXPORTS Java_Hello_sayHello


Note that it is not a mandatory file for our example. To produce the library, we just call gcc with the -shared argument. This is for Windows and Linux users.

$gcc -shared -o hello.dll hello.o hello.def  For Mac users, however, we must adapt this linking phase because the -shared option is not supported on Mac OS X. All is explained in Core Java APIs on Mac OS X. Instead, we have to use the -dynamiclib flag. If we look at the gcc documentation, e.g. man gcc, we see that -dynamiclib When passed this option, GCC will produce a dynamic library instead of an executable when linking, using the Darwin libtool command.  Thus, here is how to end up correctly: $ gcc -dynamiclib -o libhello.jnilib hello.o -framework JavaVM


This should create the file libhello.jnilib. Then, we can test our example by issuing

\$ java Hello
Hello world!


The complete source code is available here: 032_JNI.zip.