Search code examples
c++arraysheaderextern

cpp Having trouble declarning global 2d arrays


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.


Solution

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