I'm turning a sketch into a library, but I'm running into a problem when it comes to passing const int values.
My sketch uses a few constants at the top, mainly to define the sizes of some arrays.
These need to be able to be set by the user, but obviously I don't want them to have to edit the .cpp file just to set those values. However I can't seem to figure out how to have them pass the values from their own sketch to my library in such a way that they are seen as constants at compile time, since otherwise the compiler throws errors at me for giving variable array sizes.
Is there any way to do this?
tl;dr + example:
(in library.cpp)
cont int Amount = 3;
int Data[Amount];
How do I make it so someone can set the Amount variable from their sketch without having to edit library.cpp
AWOL:
you didn't think we'd be interested in seeing them?
I figured the error surrounding not being able to declare variable array sizes was pretty common and well known, and isn't really part of the issue since I know that to be the case
EDIT:
Well, I just tried it again in a quick sketch, and now I can compile a variable assigned array just fine. I've never been able to do that before, must be a new version thing
Delta_G:
forward declaration:
in library.cpp:
extern const int amount;
int Data[amount];
in sketch.ino:
const int amount = 3;
The extern declaration lets the library know that there exists a variable by that name but it will be defined somewhere else.
Thanks, that's a good start, but is there no way of just passing it to the constructor somehow?
EDIT: Well, I tried this, and now the compiler is just having a conniption fit, it's been stuck on "compiling sketch" for 10 minutes now
I've managed to recreate the array size error after all:
int foo = 3;
int bar[foo];
This will only work if sensorAmount is a const int, otherwise it spits out
sketch_aug22b:9: error: array bound is not an integer constant before ']' token
I've found this only goes for arrays declared globally, though. Inside of a loop it seems to work just fine
I've attempted Delta's way of forward declaration but that just locks up the entire compiler at about 20%
I know how to pass a regular variable to the constructor, but the problem here is that apparently I can't use those, I need either a constant or a #define statement, neither of which I know how to pass to a library
Isn't that mostly for dynamic memory allocation, though? This is pretty static, it never changes during runtime. I'm not too familiar with memory allocation and how to use it to be fair
Isn't that mostly for dynamic memory allocation, though? This is pretty static, it never changes during runtime. I'm not too familiar with memory allocation and how to use it to be fair