0

Im trying to declare a global scope variable that i want to be accessible in all my other cpp files that in include my header file but am having some trouble.

So i have a Header File "AnimationManger.h":

extern const int NUM_ANIMS;
extern const int ANIM_FRAMES;

and my "AnimationManager.cpp" file containing:

#include "AnimationManager.h"
const int NUM_ANIMS = 8;
const int ANIM_FRAMES = 4;

int animArray[NUM_ANIMS][ANIM_FRAMES];

//other functions

I want to reference my animArray variable in other cpp files that i include AnimationManager.h.

Im new to cpp, having been programming with csharp as a hobby for quite a few years now im having a little trouble fully wrapping my head around how scope works in cpp, since the concept seems quite foreign to me.

msp
  • 3,272
  • 7
  • 37
  • 49

1 Answers1

0

Move the following lines to the .h file.

const int NUM_ANIMS = 8;
const int ANIM_FRAMES = 4;

and declare the array right after that as an extern variable.

extern int animArray[NUM_ANIMS][ANIM_FRAMES];

After that, the only thing left to do in the .cpp file is define the array.

#include "AnimationManager.h"

int animArray[NUM_ANIMS][ANIM_FRAMES];

Im new to cpp, having been programming with csharp as a hobby for quite a few years now im having a little trouble fully wrapping my head around how scope works in cpp, since the concept seems quite foreign to me.

I hope you are using one or more good books to learn the language. Please visit The Definitive C++ Book Guide and List and pick a good book to learn from, if you haven't done that already.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thank you, that solved my problem. So *extern* is suppose to be used *Not* to initially define a variable, but to define that the variable with the same name already exists and to reference the initial variable? – WeirderChimp Feb 28 '18 at 07:50