So... I suspect this is a result of my never having properly learned c++, but I'm trying to port an arduino project into c++ via platformio, and I'm having a bit of a head-scratch moment. Turning to the community for help =)
Say I have four files:
// fileone.cpp
#include "utilities.h"
boolean question_is_stupid = false;
int result = answer_the_question(); // should be 0
// filetwo.cpp
#include "utilities.h"
boolean question_is_stupid = true;
int result = answer_the_question(); // should be 1
// utilities.h
int answer_the_question();
// utilities.cpp
int answer_the_question() {
if (question_is_stupid) return 1;
else return 0;
}
How can I structure this so that answer_the_question()
has access to the variable question_is_stupid
in both of the cpp files?
Obviously in this simple example, I could just pass the variable, but I'm hoping to extrapolate the answer to a much more complex codebase. Essentially, I want to pull functions used by both fileone.cpp
and filetwo.cpp
into a separate utilities
file, so that I don't have to write/edit/mess up the same function in two places. Some of my functions reference many (say, 10) global variables, so it'd be a pain (and confusing) to have to pass them all in. Is this just not done in cpp and I need to get over it? Or... is there a way?