Good morning,
I have a sketch similar to the following one:
int my_func(); // function declaration
int a = my_func(); // function call
void setup()
{
// do something
}
void loop()
{
// do something
}
int my_func() // function definition
{
// do something
return 1;
}
The preceding sketch compiles and runs without any problems; however, I need my_func to be a void function that returns nothing. I therefore change the above sketch:
void my_func(); // function declaration
my_func(); // function call
void setup()
{
// do something
}
void loop()
{
// do something
}
void my_func() // function definition
{
// do something
}
This time, I get the error message: error: expected constructor, destructor, or type conversion before ';' token.
It seems like if a function returns int (or float or whatever...), then the compiler correctly recognize the function declaration, definition and call; otherwise if a function returns nothing (void), then the compiler make confusion between function declaration and function call.
What did I do wrong?
How can I call a void function outside setup and loop?
when would you then expect the compiler to call this?
when you use a function call as an initialiser, the compilers knows it needs to call the function once it allocates the variable to get the initial value (so when you want to use it) but if it's just hanging in there in the code, then it's not working. ➜ put that in setup()
Thank for your replies!
Basically, first of all, I need to initialize several objects (something like Serial.begin(), tft.begin(), SD.begin()); this is the purpose of the aforementioned void function. Only after that do, I have to instantiate an object that is used by many functions throughout the sketch. Therefore, I decided to instantiate it before setup, in order to make it a global variable. However, by doing so, I am also required to initialize the other objects (Serial.begin(), SD.begin(), ...) outside of setup because they must be initialized before the global variable.
I'm open to any kind of advice to improve the structure of the code and make it workable
Your explanation doesn't make much sense. But you can make a global pointer to an object of the class and then instantiate / initialize it dynamically within the setup() function.
I found a solution by developing an external class with several methods.
Before setup, I create an instance of this class, making the instance, its attributes and methods accessible globally throughout the sketch. In setup I use this class' .begin() method to initialize the objects I need. The aformentioned void my_func become another method of the same class, so I can use it wherever I need.
Thank you all for your help