Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

c++ - undefined reference to `JNI_CreateJavaVM' linux

I'm trying to get familiar with the JNI API but can't get a sample c++ program to compile.

Here is the command I'm using to compile and below that is the program I'm trying to compile. The error I get is:

/tmp/cczyqqyL.o: In function `main':
/home/nc/Desktop/jni/simple/ctojava/callJava.cpp:16: undefined reference to `JNI_CreateJavaVM'

Compile:

g++ -g -I/usr/lib/jvm/java-7-oracle/include/ -I/usr/lib/jvm/java-7-oracle/include/linux/ -L/usr/bin/java -L/usr/lib/jvm/java-7-oracle/jre/lib/amd64/server/ -ljvm callJava.cpp

C++:

#include <jni.h> /* where everything is defined */

int main(){
    JavaVM *jvm; /* denotes a Java VM */
    JNIEnv *env; /* pointer to native method interface */

   JavaVMInitArgs vm_args;
   JavaVMOption options[1];
   options[0].optionString = "-Djava.class.path=/home/nc/Desktop/jni/simple/ctojava/";
   vm_args.version = JNI_VERSION_1_6;
   vm_args.options = options;
   vm_args.nOptions = 1;
   vm_args.ignoreUnrecognized = JNI_FALSE;

   /* Create the Java VM */
   int res = JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args); // this is what it can't find

   /* invoke the Main.test method using the JNI */
   jclass cls = env->FindClass("Hello");
   jmethodID mid = env->GetStaticMethodID(cls, "staticInt", "(I)I");
   env->CallStaticVoidMethod(cls, mid,10);

   /* We are done. */
   jvm->DestroyJavaVM();
}

I've searched for this issue and tried every solution I've found but still I get the same error... Any help is greatly appreciated!

EDIT: Joni's answer below works (depending on your compiler). In case someone else finds this: when running the compiled output don't forget LD_LIBRARY_PATH=_path_to_your_libjvm.so_ or it will not be able to find that lib at runtime.

LD_LIBRARY_PATH=/usr/lib/jvm/java-7-oracle/jre/lib/amd64/server ./a.out
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way GCC finds symbols was changed fairly recently: now the units to be linked are processed strictly from left to right, and references to libraries (-lYourLibrary) are silently ignored if nothing to their left in the command line needs them.

To fix this, move -ljvm after the compilation units that use it, for example to the very end of the command line:

g++ -g -I/usr/lib/jvm/java-7-oracle/include/ -I/usr/lib/jvm/java-7-oracle/include/linux/ 
-L/usr/bin/java -L/usr/lib/jvm/java-7-oracle/jre/lib/amd64/server/ callJava.cpp -ljvm

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...