Search code examples
c++compiler-errorsjava-native-interfaceglobal-variablesextern

Compiler error using global variables 'extern' in header files in C++


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.


Solution

  • 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.