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?

yesbutmaybeno
  • 1,078
  • 13
  • 31
  • 1
    Try `g++ mylibrary.cpp -o mylibrary.so -shared -fPIC`. – Kerrek SB Mar 23 '15 at 18:15
  • Btw that's not a "Java native library", it's a "native library". – m0skit0 Mar 23 '15 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? – yesbutmaybeno Mar 23 '15 at 23:20
  • 1
    @FTLRalph: Add `-m64` maybe? – Kerrek SB Mar 23 '15 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! – yesbutmaybeno Mar 24 '15 at 00:04
  • No worries, though if your operating system requires you to reboot in order to update an environment variable, perhaps that says something about your operating system... :-S – Kerrek SB Mar 24 '15 at 02:06

1 Answers1

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
Community
  • 1
  • 1
Om.
  • 2,532
  • 4
  • 22
  • 22