Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ extern variable not visible

Tags:

c++

extern

I use extern variable for my application class so i can forward class function to glutDisplayFunction(funcPtr).

main.cpp:

#include "main.hpp"

int main(int argc, char** argv)
{
  gApp = new GameApp();
  return 0;
}

main.hpp:

#ifndef MAIN_HPP
#define MAIN_HPP
  #include "GameApp.hpp"
#endif

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

This is the output:

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

I expected gApp to be visible in my main.cpp and in GameApp class.

like image 422
duke_nukem Avatar asked Nov 20 '25 17:11

duke_nukem


1 Answers

That's not a compile error, it is a link error. You variable declaration is visible just fine in main.cpp, but you haven't defined it anywhere - i.e. you don't allocate space for that variable anywhere.

You'll need one (and exactly one) C++ file that defines that variable. Possibly your main.cpp:

GameApp *gApp;

(You could initialize it too right there, but that is not necessary in this case.)

like image 143
Mat Avatar answered Nov 23 '25 07:11

Mat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!