java - CMake 对 `JNI_CreateJavaVM' 的 undefined reference

标签 java c++ cmake jvm java-native-interface

我需要从 C++ 运行 Java,一般来说这个问题已经解决,但是我的 make 系统或脚本有问题。

我有一个创建 JVM 的 C++ 文件:

#include <jni.h>
#include <iostream>
#include <string>

using namespace std;

int main() {
    JavaVMOption jvmopt[1];
    jvmopt[0].optionString = const_cast<char *>("-Djava.class.path=.");

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

    // Create the JVM
    JavaVM *javaVM;
    JNIEnv *jniEnv;
    long flag = JNI_CreateJavaVM(&javaVM, (void **)
            &jniEnv, &vmArgs);

    return 0;
}

我有一个 CMakeLists.txt 文件:

cmake_minimum_required(VERSION 3.12)
project(games_test_system)

include_directories(/usr/java/jdk-10.0.2/include /usr/java/jdk-10.0.2/include/linux)
link_directories(/usr/java/jdk-10.0.2/lib /usr/java/jdk-10.0.2/lib/server)

set(CMAKE_CXX_STANDARD 14)

add_executable(games_test_system main.cpp)

我运行它:

/opt/clion-2018.2.2/bin/cmake/linux/bin/cmake --build /home/obabichev/CLionProjects/games-test-system/cmake-build-debug --target games_test_system -- -j 4

但是我得到这个错误:

[ 50%] Linking CXX executable games_test_system
CMakeFiles/games_test_system.dir/main.cpp.o: In function `main':
/home/obabichev/CLionProjects/games-test-system/main.cpp:21: undefined reference to `JNI_CreateJavaVM'
collect2: error: ld returned 1 exit status
CMakeFiles/games_test_system.dir/build.make:83: recipe for target 'games_test_system' failed
make[3]: *** [games_test_system] Error 1
CMakeFiles/Makefile2:72: recipe for target 'CMakeFiles/games_test_system.dir/all' failed
make[2]: *** [CMakeFiles/games_test_system.dir/all] Error 2
CMakeFiles/Makefile2:84: recipe for target 'CMakeFiles/games_test_system.dir/rule' failed
make[1]: *** [CMakeFiles/games_test_system.dir/rule] Error 2
Makefile:118: recipe for target 'games_test_system' failed
make: *** [games_test_system] Error 2

我感觉是连接器的问题,但具体是什么问题我不明白。

最佳答案

在你的CMakeLists.txt文件中,添加

find_package(JNI REQUIRED)
target_link_libraries(games_test_system ${JNI_LIBRARIES})

除了手动选择目录,您还可以依赖 CMake:

include_directories(${JNI_INCLUDE_DIRS}

关于java - CMake 对 `JNI_CreateJavaVM' 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51986247/

相关文章:

java - libGDX And​​roid 项目上的 Box2dLights

Java-spring错误: Actual and formal argument differ in length

java - 在java中组合比较器

c++ - 我可以通过使用多线程更快地分配内存吗?

CMake:使用自定义工具输出生成标题

c++ - 多项目 cmake 不工作

c++ - 未定义对使用CMake生成为lib .a的方法的引用

java - OnCreateOptions 被调用,但 OnOptionsItemSelected 未被调用

c++ - x86-64 程序集 : why offset 25 bytes?

c++ - 现金流的财务建模中的继承与特定类型