A list of steps on how to run a C/C++ function from a Java Program on MacOS Sierra. The example files for HelloWorld.java
, HelloWorld.h
, and HelloWorld.cpp
are provided.
- Creating the Java Class
- Compiling the Java Class
- Creating the C++ code
- Compiling the C++ code
- Compiling the Java Program with the Native Library
- Using the Shell Script
Create a new file HelloWorld.java:
class HelloWorld {
private native void print();
public static void main(String[] args) {
new HelloWorld().print();
}
static {
System.loadLibrary("HelloWorld");
}
}
To compile the Java Class, run the command:
$ javac HelloWorld.java
To generate the header file for the C++ code, run the command:
$ javah -jni HelloWorld
This will output the following file HelloWorld.h:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloWorld */
#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: HelloWorld
* Method: print
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloWorld_print
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Create a new file HelloWorld.cpp:
#include <jni.h>
#include <iostream>
#include "HelloWorld.h"
using namespace std;
JNIEXPORT void JNICALL
Java_HelloWorld_print(JNIEnv *, jobject){
cout << "Hello World!\n";
return;
}
Compiling the C++ Code to include the jni.h library is going to be the most difficult part of this process.
To start, run the command:
$ export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
and then:
$ g++ -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/darwin/" -o HelloWorld.o -shared HelloWorld.cpp
This will create the file HelloWorld.o. Finally run:
$ g++ -dynamiclib -o libhelloworld.jnilib HelloWorld.o
Finally, to run the Java Program, run:
$ java HelloWorld
The ouput should be:
Hello World!
The shell script simply runs all of these commands:
#!/bin/bash
javac Helloworld.java
javah -jni HelloWorld
export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
g++ -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/darwin/" -o HelloWorld.o -shared HelloWorld.cpp
g++ -dynamiclib -o libhelloworld.jnilib HelloWorld.o
java HelloWorld
Running the provided shell script with the command:
$ ./build.sh
will complete all of these steps and run the HelloWorld.java program. If permissions are denied, you may have to run:
$ chmod -x build.sh
Like running the java executable, running this script will output:
Hello World!