I'm currently working on an Atmega2560-based hardware project, and I've written about 2000 lines of C++ code - which is now getting unmanageable. It's a project for a local community, and maintainability is important, so I'm trying to pull everything out into modules and keep things simple, so that someone with even less understanding of C++ that I have could at least understand what's going on.
At the heart of the project is a global multidimensional integer array, initially declared in main.cpp (where it worked fine with all functions contained in main.cpp):
// main.cpp
const int A = 30;
const int B = 20;
const int C = 10;
int gArray[A][B][C];
If I do the same in GLOBAL.h, it compiles fine - so, clearly, A, B and C are accepted as constants. But it doesn't work across the modules. If in a code module I use:
// setup.cpp
extern const int A;
extern const int B;
extern const int C;
extern int gArray[A][B][C];
I get the "array bound is not an integer constant before ']' token" error.
So my question is basically - how can I use a global multidimensional array across several modules with the fixed dimensions set in a single place for maintainability?
I've been trying for some to sort this, reading and trying lots of ideas I've read, but I've not been able to make any progress. In the meantime I've created functions to set and to read array values and placed them in GLOBALS.h - which seems inelegant, but is an understandable and practical workaround:
const int A=30;
const int B=20;
const int C=10;
int gARRAY[A][B][C];
void setARRAY(int A, int B, int C, int V) {
gARRAY[A][B][C] = V;
}
int getARRAY(int A, int B, int C) {
return gARRAY[A][B][C];
}
SOLVED!!!
First of all, mea culpa - in following the suggestions using
gArray[30][20][10]
, I hadn't noticed that I'd exceeded the RAM capacity!! So, when I might have had what should have been a working method, the processor was crashing [no compiler warnings]. The reality is that I actually only needgArray[10][13][10]
The result of fixing this and using the tips from the kind comments made it work.
In case anyone else needs to do use global multidimensional arrays, here's how I did it [note that I'm using the Arduino environment, so there's no
int main()
for instance]:First, in
GLOBALS.h
I set the dimensions#defines
and then declared the array inGLOBALS.cpp
:I then created a couple of test modules
setup.h & setup.cpp
to initialise array values andtestaccess.h & testaccess.cpp
to change the values, as well asmain.cpp
to test it out [containing the Arduinovoid setup()
andvoid loop()
, the latter isn't shown as it's empty]:and in
testaccess.h & testaccess.cpp
I modified the two test values:Finally, in my main code I did the testing:
... and the result on the serial port was ...
After two weeks of struggling, I can now move on!
Thanks all for the help and inspiration.