Let's say I have a main function as follows:
The "applyDutyFactor" function is defined in a header file called "PWM.h" as follows:
I have a few similar situations to this, where I need a function defined in a header file to be able to "see" a variable which is declared elsewhere. I have been getting round this by using the "extern" keyword to let the compiler know that the variable does indeed exist somewhere. However, I have heard it said that using too many global variables like this is bad practice. I now have around 20 global variables in my program because of the above issue.
Question: Is what I am doing really bad practice? If so, what is the preferred way to access a variable that is declared elsewhere? Should I pass every variable into the function as an argument instead?
Code:
int pwmPeriod = 10000;
void main(void)
{
while(1)
{
float duty = 0.5;
applyDutyFactor(duty);
}
}
Code:
void applyDutyFactor(float duty)
{
extern int pwmPeriod;
PWM_COMPARE_REGISTER_NAME = duty * pwmPeriod;
return;
}
Question: Is what I am doing really bad practice? If so, what is the preferred way to access a variable that is declared elsewhere? Should I pass every variable into the function as an argument instead?