Hi, I have recently started to develop locally. As my app grows, I find myself distracted by a bunch of functions at the beginning of my one application.cpp file. I am looking for a way to clean up my code. I know I could write a few libraries for them, but the functions are very diverse and rather unconnected - I would prefer to simply move them to a separate file to have them put of the way, and to somehow bake them into the compilate.
I am pretty new to c++ and could not find anything that made me feel I was on the right track. Maybe someone can help? I’d be glad!
Oh, that was easy. Great! One question though, if you don’t mind.
When I do define a configuration const in application.cpp, how can I make it be seen in my new external function file as well?
let’s say you have this const in your .cpp file:
const int magicNumber = 42;
Then you declare it in the header file like this:
extern const int magicNumber;
What this tells the compiler is that somewhere, there is a constant, and then it is resolved at link time.
There is also an easier option - move the const to the header file - simply copy and paste:
const int magicNumber = 42;
Then include the header whenever you need to access the constant. Most compilers optimize away the storage for the constant, unless you take the address of the constant.
const int RGB_FEEDBACK_DURATION = 250;
#include "helpers.h"
helpers.h:
#include "application.h"
extern const int RGB_FEEDBACK_DURATION;
void rgb_black ();
helpers.cpp:
#include "helpers.h" // I added this because of (A), see below.
void rgb_black () {
RGB.color(0, 0, 0);
delay (RGB_FEEDBACK_DURATION);
}
Even though I honestly don’t know what I am doing here, the reasons for adding (A): The compiler would complain about not declared in this scope for RGB, which is a built-in library, and RGB_FEEDBACK_DURATION.
What’s the status now? The compile error goes away. (error: 'RGB_FEEDBACK_DURATION' was not declared in this scope)
I now have a new (linker?) error, undefined reference to 'RGB_FEEDBACK_DURATION'
Try putting “helpers.h” before RGB_FEEDBACK_DURATION in application.cpp - that should fix the linker problem.
The reason you had to include helpers.h in helpers.cpp is to also include application.h (which is in helpers.h) - this includes all the built-in libraries, including, RGB.color().