我正在尝试熟悉JNI API,但无法获得要编译的示例c ++程序。
这是我用来编译的命令,下面是我正在尝试编译的程序。我得到的错误是:
/tmp/cczyqqyL.o: In function `main':
/home/nc/Desktop/jni/simple/ctojava/callJava.cpp:16: undefined reference to `JNI_CreateJavaVM'
编译:
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();
}
我已经搜索过这个问题并尝试了我找到的所有解决方案,但我仍然遇到同样的错误......非常感谢任何帮助!
编辑:Joni的答案可行(取决于您的编译器)。如果其他人发现这一点:在运行编译输出时不要忘记LD_LIBRARY_PATH = _path_to_your_libjvm.so_,否则它将无法在运行时找到该lib。LD_LIBRARY_PATH=/usr/lib/jvm/java-7-oracle/jre/lib/amd64/server ./a.out
答案 0 :(得分:20)
GCC最近发现符号的方式发生了变化:现在要链接的单元从左到右严格处理,如果在命令行中没有任何内容,则会默默忽略对库(-lYourLibrary
)的引用需要它们。
要解决此问题,请在使用它的编译单元之后移动-ljvm
,例如移到命令行的最后:
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