c++ - 在 C++ 的头文件中使用全局变量 'extern' 的编译器错误

标签 c++ compiler-errors java-native-interface global-variables extern

我正在使用 Java Native Interface 并试图使 JNIEnv 环境指针 (*env) 成为全局变量。我将 eclipse 与 g++ 一起使用,我有以下文件:

自定义库.hh

#ifndef CUSTOMLIBRARY_HH_
#define CUSTOMLIBRARY_HH_

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

#endif /* CUSTOMLIBRARY_HH_

主.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();
}

我的类.cpp
#include "CustomLibrary.hh"

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

但是,每当我尝试构建项目时,都会出现以下错误:
myclass.cpp: undefined reference to 'env'

我不完全确定问题是什么。

最佳答案

这里的问题是范围之一。

extern JNIEnv *env;

是在全局范围内。这意味着它是一个不同的变量
JNIEnv *env = nullptr;

您在 main 中声明的, 因为它的范围是 main .你需要把
JNIEnv *env = nullptr;

在单个 cpp 文件的全局空间中,以便对其进行定义。

关于c++ - 在 C++ 的头文件中使用全局变量 'extern' 的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53379499/

相关文章:

c++ - TCP over IPv4 的最小数据包大小是多少

c++ - 错误 : variable or field ‘myfunction’ declared void

android - 将 Kinect 连接到安卓

c++ - 如何完全删除二维指针数组

c++ - 将 C++ 代码从 VS2003 迁移到 VS2010 后出现错误 C2678,错误 C2679 : binary '=' : no operator found which takes a right-hand operand of type 'int'

c++ - 防止在 Visual Studio 调试期间进入 "memory"

objective-c - 如何在类里面要求 ARC?

ruby - 无法编译 ruby​​ 1.9.3

java - 如何通过JNI操作CameraPreview bytearray? (开放式简历)

java - JNI方法静态解析验证