# Best Place to Declare a Struct that I want to Access in a Function but Only Initialize Once

#### TechWise

Joined Aug 24, 2018
144
Let's say I have a function within my main loop which contains some control algorithm.

Code:
void main(void)
{
// Various things which happen once...
while(1)
{
if(timerInterruptHasOccured == 1)
{
myControlAlgorithm();
timerInterruptHasOccured = 0;
}
}
}
Within my control algorithm, I have a several PID controllers. I have defined and typedefed a struct, "PID_data" to wrap up all of the gains and previous values which need to be stored for the next iteration. I've hit a bit of a conundrum regarding where to declare any instances of this struct.
1. Option 1 - Declare "PID_data controller_one;" in main(). This makes it really easy to call an initialization function to set the gains at startup and then I can pass "&controller_one" as an argument to myControlAlgorithm(); so that the data can be accessed. I don't really like this though because it means if I want to use a different control algorithm, I need to remember to not only change the function, but to also declare whatever instances of "PID_data" it happens to need and then pass their addresses.
2. Option 2 - Declare "static PID_data controller_one;" inside "myControlAlgorithm()". This is the more robust option I think because then I can simply call "myControlAlgorithm()", safe in the knowledge that it will declare whichever variables it needs for itself without me having to declare them in main(). However, this makes it more difficult to have a one-time initialization function to set the gains, because the PID_data structs will not be visible outside of myControlAlgorithm(). This then leads me down the route of having some static variable like "static int isInitialized" which I have to test everytime myControlAlgorithm() is called which seems a bit inefficient.
3. Option 3 - Some better way that I haven't thought of that the good people of AAC would like to suggest below....

As I've stated in previous threads, I'm trying to build good coding practices so I appreciate any and all thoughts on the matter. How would you approach this?

#### dl324

Joined Mar 30, 2015
12,265
The "best" place is subjective and is sometimes a matter of style.

If the struct will be used in multiple source files, the declarations should be placed in an include file that tests to make sure it isn't included more than once.

If all of the code is in one file, the only reason for splitting it into a separate file is "style" or if it might be used by other programs.