May 22, 2009

Building a c++ dynamic library on 64-bit Intel OSX

It seems like every JNI example for OSX depends on XCode. So here is a simple example of how to build a dynamic library, for OSX, from the command line:

g++ -m64 -c -I/System/Library/Frameworks/JavaVM.framework/Headers Foo.cpp
g++ -m64 -dynamiclib -o libfoojni.jnilib Foo.o -framework JavaVM

Without the -m64 argument you will receive the unintuitive error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: /development/sandbox/libfoojni.jnilib:
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1822)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1739)
at java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1030)
at Foo.(Foo.java:7)