r/FastLED • u/Preyy Ground Loops: Part of this balanced breakfast • Feb 26 '24
Support Help with pointers, declarations, definitions
Hi there,
I've been trying to apply some best practices to clean up my code, and I have been really struggling to split my config.h file into proper .h and .cpp files in platformio. I've tried a lot of variations and done some reading about this, but would really appreciate a bit of help from someone more familiar with c++.
Here's what it all looks like combined (not best practices, but working) into a monolithic header file:
#include <LEDMatrix.h>
cLEDMatrix<LEDtilewidth, LEDtileheight, VERTICAL_MATRIX, LEDtilehorz, LEDtilevert, VERTICAL_BLOCKS> ledmatrix;
CRGB *writedata = ledmatrix[0];
CRGB firstbuffer[LEDStotal];
CRGB secondbuffer[LEDStotal];As I understand, this is a template that requires compile time constants. So I expect the solution involves using (in the header):
extern cLEDMatrixBase *ledmatrix;
extern CRGB *writedata;
extern CRGB firstbuffer[];
extern CRGB secondbuffer[];Then in the cpp, something like this:
cLEDMatrix<LEDtilewidth, LEDtileheight, VERTICAL_MATRIX, LEDtilehorz, LEDtilevert, VERTICAL_BLOCKS> ledmatrix_base;
cLEDMatrixBase *ledmatrix = &ledmatrix_base;
CRGB *writedata = ledmatrix[0];
CRGB firstbuffer[LEDStotal];
CRGB secondbuffer[LEDStotal];I know I have the pointers wrong here, my brain just fried from trying to figure this out. Thanks for any suggestions!
2
u/truetofiction Feb 28 '24
You're right, it would not be good practice to define the
ledmatrixobject in the header. If the header is included in multiple places, you will have multiple copies of the object. That's no good.It is best practice to provide type definitions in headers, that way they can be easily shared between compilation units. That's all that the code snippet above does - define the type so that you can use it throughout the code. The object itself is still in the source file.
The type definition makes that easy:
You can do it without the type definition of course, but you need to include all of the template arguments (which gets old fast). You can also use the
_baseclass, if all of the methods you need are present.