-2

I'm using the Java Native Interface and trying to make the JNIEnv environment pointer (*env) a global variable. I'm using eclipse with g++ and I have the following files:

CustomLibrary.hh

#ifndef CUSTOMLIBRARY_HH_
#define CUSTOMLIBRARY_HH_

#include <jni.h>
extern JNIEnv *env;

#endif /* CUSTOMLIBRARY_HH_

main.cpp:

#include <jni.h>
#include "CustomLibrary.hh"

int main()
{
    //create java virtual machine

   JavaVM *javaVM = nullptr; 
   JNIEnv *env = nullptr;
   long flag = JNI_CreateJavaVM(&javaVM, (void**)&env, &vmArgs);

   if (flag == JNI_ERR)

   //call some other class method which uses the env global variable
   myclass MYCLASS();
   MYCLASS::doSomething();
}

myclass.cpp

#include "CustomLibrary.hh"

myclass::doSomething()
{
    anotherFunction(env);    
}

However, whenever I try to build the project I get the following error:

myclass.cpp: undefined reference to 'env'

I'm not entirely sure what the problem is.

kahamster
  • 51
  • 5
  • You need a global variable definition of `env` to match your declaration. Your `myclass MYCLASS();` won't do what you expect it to do, and `myclass MYCLASS::doSomething();` is not valid. I strongly recommend you read a C++ book if you are planning to program this language. – SergeyA Nov 19 '18 at 17:07
  • Oops meant to put MYCLASS::doSomething() – kahamster Nov 19 '18 at 17:21

1 Answers1

1

The problem here is one of scope.

extern JNIEnv *env;

is in the global scope. That means it is a different variable from

JNIEnv *env = nullptr;

that you declare in main, since it is scoped to main. You need to put

JNIEnv *env = nullptr;

in the global space of a single cpp file in order for it to be defined.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402