3
votes

I am trying to start the jvm using c++ . Here is My CmakeLists.txt and ny C++ code.

My System is macOS Mojave 10.14.6

Java using homebrew cask install

openjdk version "1.8.0_232"

OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_232-b09)

OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.232-b09, mixed mode)

cmake_minimum_required(VERSION 3.15)
project(jvm)

set(CMAKE_CXX_STANDARD 14)

include_directories(
        /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/include
        /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/include/darwin
)

link_libraries(
        /System/Library/Frameworks/JavaVM.framework/JavaVM
)

add_executable(jvm main.cpp)
#include <iostream>
#include "jni.h"

using namespace std;

int main() {
    std::cout << "Hello, World!" << std::endl;
    JavaVM *jvm;
    JNIEnv *env;

    JavaVMOption jvmopt[3];
    jvmopt[0].optionString = "-Djava.compiler=NONE";
    jvmopt[1].optionString = "-Djava.class.path=./"; 

    jvmopt[2].optionString=  "-verbose:class";

    JavaVMInitArgs vmArgs;
    vmArgs.version = JNI_VERSION_1_8;
    vmArgs.nOptions = 1;
    vmArgs.options = jvmopt;
    vmArgs.ignoreUnrecognized = JNI_TRUE;

    long  flag = JNI_CreateJavaVM(&jvm, (void **) &env, &vmArgs);
    cout << flag << endl;

    jvm->DestroyJavaVM();
    return 0;
}

The result of the main function run

JavaVM: Failed to load JVM: /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bundle/Libraries/libserver.dylib
JavaVM FATAL: Failed to load the jvm library.

[UPDATE]

PROBLEM SLOVED !!!

The reason is I link the wrong library.

I should link $JAVA_HOME//lib/server/libjvm.dylib

What's more , I use oracle JDK instead of openjdk. Maybe something wrong with openjdk!!

2
vmArgs.nOptions = 1; -- Shouldn't this be vmArgs.nOptions = 3;?PaulMcKenzie
I try but still the same @PaulMcKenziesteven chan
Well, I know that in Windows, the jvm (in the case of Windows, jvm.dll) and related libraries must be on the path. Your error seems to suggest that the system cannot find these libraries.PaulMcKenzie
Do you know which file is the same as jvm.dll in windows?steven chan

2 Answers

24
votes

Steps to resolve the issue (JavaVM: Failed to load JVM:.../libserver.dylib):

cd /Library/Java/JavaVirtualMachines/jdk1.8.0_271.jdk/Contents/Home
cd lib

Create a softlink libjvm.dylib as libserver.dylib:

sudo ln -s ../jre/lib/server/libjvm.dylib libserver.dylib
2
votes
sudo ln -s /Library/Java//JavaVirtualMachines/jdk1.8.0_74.jdk/Contents/Home/jre/lib/server/libjvm.dylib /Library/Java/JavaVirtualMachines/jdk1.8.0_74.jdk/Contents/Home/lib/libserver.dylib

alternatively that worked for me