JNI - “Cannot open include file: 'jni_md.h'

2019-01-26 02:38发布

问题:

This sample program is meant to call a native method written in C.

Java Code

class HelloWorld {

    private native void print();

    public static void main( String args[] ) {
        new HelloWorld().print();
    }

    static {
        System.loadLibrary("HelloWorld");
    }

}

After writing this i compiled the program and generated a JNI style header file.

The header file generated is :

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <C:\Program Files\Java\jdk1.7.0\include\jni.h>
/* Header for class HelloWorld */

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloWorld
 * Method:    print
 * Signature: ()V
 */
 JNIEXPORT void JNICALL Java_HelloWorld_print
 (JNIEnv *, jobject);

 #ifdef __cplusplus
 }
 #endif
 #endif

And the native method written in c

#include <C:\Program Files\Java\jdk1.7.0\include\jni.h>
#include <C:\Program Files\Java\jdk1.7.0\include\win32\jni_md.h>
#include <stdio.h>
#include "HelloWorld.h"

JNIEXPORT void JNICALL Java_HelloWorld_print( JNIENv *env , jobject obj) {
    printf("Hello World!\n");
    return;
}

The error I get on compiling is fatal error C1083: Cannot open include file: 'jni_md.h': No such file or directory

Also my compiler underlines jobject obj saying that this class does not have storage class or specifier . It underlines *env saying expected a ')'.

Why do I get this error ?

回答1:

I suspect that jni.h is trying to #include <jni_md.h>, which is then failing because you haven't added its location to your include path.

Try adding both of these entries to your C compiler's include path:

  • C:\Program Files\Java\jdk1.7.0\include
  • C:\Program Files\Java\jdk1.7.0\include\win32

The win32 path might not be necessary, depending on how jni.h is set up.



回答2:

Try this,

HelloWorld.c

#include "HelloWorld.h"
#include <stdio.h>

JNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj)
{
  printf("Hello World!\n");
  return;
}

Compile it using cl.exe (I'm using VC++ and CL.EXE required following command line switches.)

c:\>cl -c /I"c:\Program Files\java\jdk1.7.0\include" /I"c:\Prog ram Files\java\jdk1.7.0\include\win32" HelloWorld.c

Link .obj module

c:\>link /libpath="c:\Program Files\java\jdk1.7.0\lib" HelloWorld.obj /dll



回答3:

I had this issue once, my solution was actually to edit the jni.h's internal #include from "jni_md.h" to "win32/jni_md.h", although there is probably a less hacky way you are supposed to do it.



回答4:

Just copy jni_md.h file to folder where jni.h.