4

I hope that's the right word to use, "compile." I'm asking here since I'm not even sure what to Google for to get more information.

I want to use this library here: http://jiggawatt.org/badc0de/android/#gifflen

The download gives a bunch of .cpp and .h files. From what I understand, I need a .so file in order to use System.loadLibrary(libName).

What I can't figure out is how to compile these C++ files into the necessary .so file?

6
  • 1
    Try g++ mylibrary.cpp -o mylibrary.so -shared -fPIC. Commented Mar 23, 2015 at 18:15
  • Btw that's not a "Java native library", it's a "native library". Commented Mar 23, 2015 at 18:35
  • @KerrekSB Alright, so I went and downloaded/installed MinGW and ran the command above. It worked. However, now when I attempt to use the library, I get Can't load IA 32-bit .dll on a AMD 64-bit platform. How can I go about resolving this, any parameters I need or something? Commented Mar 23, 2015 at 23:20
  • 1
    @FTLRalph: Add -m64 maybe? Commented Mar 23, 2015 at 23:51
  • @KerrekSB Figured it out. I had downloaded MinGW 64 and updated by PATH variable, but didn't reboot. Was still building off of the old compiler. All good now, thanks! Commented Mar 24, 2015 at 0:04

1 Answer 1

3

You can create shared object file using below mentioned command.

gcc -shared -fpic -o <so-file-name>.so a.c b.c 

on Mac OS X, compile with:

g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so g++ class_user.cc -o class_user 

On Linux, compile with:

g++ -fPIC -shared myclass.cc -o myclass.so g++ class_user.cc -ldl -o class_user 

References:

C++ Dynamic Shared Library on Linux

Build .so file from .c file using gcc command line

Sample tutorial

Sample code to run .so file using java with commands:

HelloJNI.c

#include <jni.h> #include <stdio.h> #include "HelloJNI.h" JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) { printf("Hello World!\n"); return; } 

HelloJNI.java

public class HelloJNI { static { System.loadLibrary("hello"); // hello.dll (Windows) or libhello.so (Unixes) } // A native method that receives nothing and returns void private native void sayHello(); public static void main(String[] args) { new HelloJNI().sayHello(); // invoke the native method } } 

Steps to run above .c file using .java file

javac HelloJNI javah HelloJNI gcc -shared -fpic -o libhello.so -I/usr/java/default/include -I/usr/java/default/include/linux HelloJNI.c java -Djava.library.path=. HelloJNI 
Sign up to request clarification or add additional context in comments.

1 Comment

Note that javah was deprecated in Java 8: openjdk.java.net/jeps/313

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.