0

I am trying to compile my C++ project using CMake on my Mac M1 Pro 12.0.1.

This is my simple directory structure: enter image description here

In my foo.cpp, I am including jni.h header file:

#include <iostream>
#include "foo.h"
#include <vector>
#include <jni.h>
void foo()
{
    std::cout << "Hello World!\n";
}

This is my CMakeLists.txt:

cmake_minimum_required(VERSION 3.4.1)

project("myapplication")


add_library(my_app SHARED main.cpp foo.cpp)

target_include_directories(my_app PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})

    if(APPLE)
        
    
        set(JAVA_INCLUDE_PATH "$ENV{JAVA_HOME}/include")
        set(JAVA_INCLUDE_PATH2 "$ENV{JAVA_HOME}/include/darwin")
        set(JAVA_AWT_INCLUDE_PATH "$ENV{JAVA_HOME}/include")
        message("JAVA_INCLUDE_PATH = ${JAVA_INCLUDE_PATH}")
        find_package(JNI REQUIRED)
        if (JNI_FOUND)
            message (STATUS "JNI_INCLUDE_DIRS=${JNI_INCLUDE_DIRS}")
            message (STATUS "JNI_LIBRARIES=${JNI_LIBRARIES}")
        endif()
        target_include_directories(my_app PUBLIC ${JNI_INCLUDE_DIRS})
    endif()

I am getting CMake output as:

-- Found JNI: /System/Library/Frameworks/JavaVM.framework  
-- JNI_INCLUDE_DIRS=/Users/vmangal/Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home/include;/Users/vmangal/Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home/include/darwin;/Users/vmangal/Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home/include
-- JNI_LIBRARIES=/System/Library/Frameworks/JavaVM.framework;/System/Library/Frameworks/JavaVM.framework
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/vmangal/my/practice/cmake/build

My JAVA_HOME environment variable is set to /Users/vmangal/Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk

But during make command, I am getting compilation error:

/Users/vmangal/my/practice/cmake/foo.cpp:4:10: fatal error: 'jni.h' file not found
#include <jni.h>

Am I missing something in CMakeLists.txt ?

Vivek Mangal
  • 532
  • 1
  • 8
  • 24

1 Answers1

-1

I had a similar problem and found that when setting variables this way

    set(JAVA_INCLUDE_PATH "$ENV{JAVA_HOME}/include")

i was getting wrong imports for C_INCLUDES and CXX_INCLUDES. Like this (see in CMakeFiles/my_app.dir/flags.make):

C_INCLUDES = -I/include -I/include/darwin
CXX_INCLUDES = -I/include -I/include/darwin

Which basically which meant that $ENV{JAVA_HOME} was an empty string. After I set the full paths in CMakeLists

    set(JAVA_INCLUDE_PATH /usr/local/Cellar/openjdk@17/17.0.3/libexec/openjdk.jdk/Contents/Home/include)

everything started working correctly.

So the conclusion is that if you want to run cmake and use $ENV{JAVA_HOME} – use syntax JAVA_HOME=/path/to/java/home cmake ...