How can I use global variables in a library?

Hi,

I'm using the MegaServo library to Control a couple of servos and to avoid jitter I'm having the servo positions only updated during the reset pulse. I'm using the timer interrupt function in the MegaServo library to signal to the main scope I can update the servo positions.

Now I have placed a boolean varable in MegaServo.h and from the timer interrupt I set the flag to true when the reset puls comes in. I want to read this flag from the loop() function. Now when I compile the code I get a "multiple declaration" error. I have only declared the boolean once, so I don't understand why I get this error. I have place this var before the MegaServo class declaration.

Right now I have a workaround using digitalWrite and digitalRead on an unused pin, but that a very ugly workaround I would not like to use in the final version...

Can anyone explain how I can use a global variable I can access from both the library and the main scope?

Thanks in advance!

There are two possibilities: (possibly more)

  1. require the variable to have a certain name.

  2. send the adress of the variable as a parameter to the object.

  3. is the best/most correct way.

If you wanna know WHY, check out http://www.gidforums.com/t-16845.html

Best thing would be move the variable to the .CPP file (possibly outside the class declarations, just like you have it now in the header file). But this makes the variable only able to be seen only by that library, and not by your main sketch. But then you would add a new function to return the value of that variable. Something like

bool myVar; // declare variable in Sketch

myVar = classvar.GetBoolValue(); // returns boolean value

Good luck!

PS: you can also use "EXTERN", but I believe keeping the variable private to the library is the better way to go.

Thank you so much!

Kitep, your explanation is very clear and I am ashamed I didn't know about this even after many years of programming... I have used the solution with the function that returns the variable in the cpp file and it works great.