Search code examples
c++dlljava-native-interface

Create a dll of a c++ project with CMakeList


I would like to build a jni application using CMakeLists. I exported my java file as Test.h and implemented the native methods in my main.cpp file. Now I'd like to export the cpp project and all its dependencies (like jni) using CMakeLists as dll and import it in my java project. When I build the application (in clion) the build runs without errors and files are created. However, I can't seem to export the cpp project as dll: among all the created files (lots of .make and .cmake files) and directories there is no dll file.

This is my CMakeLists file:

cmake_minimum_required(VERSION 3.3)
project(Uebung_2_cpp)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

find_package(JNI REQUIRED)
include_directories(${JNI_INCLUDE_DIRS})

if (JNI_FOUND)
    message(STATUS "JAVA_INCLUDE_PATH2=${JAVA_INCLUDE_PATH2}")
else ()
    message(FATAL_ERROR "I really need JNI.")
endif ()

set(SOURCE_FILES
        main.cpp
        Test.h)

add_executable(Uebung_2_cpp ${SOURCE_FILES})

add_library(mylib.dll SHARED main.cpp Test.h )

I guess the last line is rubbish and should be replaced by a more accurate statement. What am I missing?


Solution

  • The last line is not rubbish. A mylib.dll file is created under a generic path C:\users....Clion12\system\cmake\generated\randomnumber\randomnumber\Release... when the build/run/debug configuration is set correctly.

    However, the .dll is not useful in that case since the java application throws UnsatisfiedLinkError. I was finally able to solve the problem by simply using the following command (which I adapted from here:

    g++ -Wl,--add-stdcall-alias -I "<JAVA_32_BIT_HOME>\include" -I"<JAVA_32_BIT_HOME>\include\win32" -shared -o <DESIRED_.dll_FILE_PATH> <IMPLEMENTATION_FILE>

    It produces a simple .dll file that can be imported into the java project and be imported using System.loadLibrary("<library>");
    A sample project can be found here.