c ++ extern变量不可见

duk*_*kem 2 c++ extern

我为我的应用程序类使用extern变量,所以我可以将类函数转发到glutDisplayFunction(funcPtr).

main.cpp中:

#include "main.hpp"

int main(int argc, char** argv)
{
  gApp = new GameApp();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

main.hpp:

#ifndef MAIN_HPP
#define MAIN_HPP
  #include "GameApp.hpp"
#endif
Run Code Online (Sandbox Code Playgroud)

GameApp.hpp:

#include <GL/gl.h>
#include <GL/freeglut.h>

class GameApp
{
  public:
  int running;

  GameApp();
  virtual ~GameApp();
  void resize(int width, int height);
  void init(int argc, char** argv, int width, int height);
  void draw();
  void update();
  void key_input(unsigned char key, int x, int y);
};

extern GameApp *gApp;

void display_clb()
{
  if (!gApp)
  {
    return;
  }

  gApp->draw();
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

g++     -o dist/Debug/GNU-Linux-x86/gravity build/Debug/GNU-Linux-x86/main.o build/Debug/GNU-Linux-x86/GBody.o build/Debug/GNU-Linux-x86/GameApp.o build/Debug/GNU-Linux-x86/GBodyList.o -lm -lGL -lglfw -lGLU -lglut 
build/Debug/GNU-Linux-x86/main.o: In function `main':
/home/viktor/Documents/cpp/Gravity/main.cpp:6: undefined reference to `gApp'
/home/viktor/Documents/cpp/Gravity/main.cpp:7: undefined reference to `gApp'
/home/viktor/Documents/cpp/Gravity/GameApp.cpp:13: undefined reference to `gApp'
/home/viktor/Documents/cpp/Gravity/GameApp.cpp:18: undefined reference to `gApp'
build/Debug/GNU-Linux-x86/GameApp.o: In function `display_clb()':
/home/viktor/Documents/cpp/Gravity/GameApp.cpp:23: undefined reference to `gApp'
build/Debug/GNU-Linux-x86/GameApp.o:/home/viktor/Documents/cpp/Gravity/GameApp.cpp:28: more undefined references to `gApp' follow
collect2: ld returned 1 exit status
make[2]: *** [dist/Debug/GNU-Linux-x86/gravity] Error 1
make[2]: Leaving directory `/home/viktor/Documents/cpp/Gravity'
make[1]: *** [.build-conf] Error 2
make[1]: Leaving directory `/home/viktor/Documents/cpp/Gravity'
make: *** [.build-impl] Error 2
Run Code Online (Sandbox Code Playgroud)

我希望gApp在我的main.cpp和GameApp类中可见.

Mat*_*Mat 8

这不是编译错误,而是链接错误.您可以看到变量声明很好main.cpp,但是您没有在任何地方定义它 - 即您不在任何地方为该变量分配空间.

您将需要一个(并且恰好一个)C++文件来定义该变量.可能你的main.cpp:

GameApp *gApp;
Run Code Online (Sandbox Code Playgroud)

(你可以在那里初始化它,但在这种情况下这不是必需的.)