I have read the following description about static:
"The static keyword can be used with global variables and functions. In this context it limits their visibility to the current file (translation unit is more precise here). This means that we cannot access a static function or variable from another source file." - Source (30.01.2018): The static keyword in C
To make that sure I wrote some simple code devided in three separated files. I loaded the following sketch on my Arduino Uno (ATMEGA328P) using the Arduino IDE 1.8.5:
1. Main File
static int foo = 7;
void setup()
{Serial.begin(9600); staticTest();}
I expected an error-message because I declared "foo" as static in my main-file (1.). But instead the function "staticTest" (2.) prints out the value of "foo" when I open the serial monitor. Can anyone help me to understand why my static variable "foo" obviously is visible for the function "staticTest" which I have in my separated .ino-File?
The Arduino IDE collects all arduino files and that is given to the compiler as a single .cpp file. Also the prototyping is done by scanning the *.ino files, but that sometimes fails.
That means the normal rules for a compiler are sometimes different for the Arduino IDE.
BulldogLowell:
your three files aren't adequately described to tell you what is happening... what is the Main file? what is the Function file?
Hello BulldogLowell,
thank you for your post. I used the term "main file" for the file where I also have my void loop inside which is just empty (therefore I just skipped the loop here).
the "function file" is my second ino-file where I have placed the function "staticTest".
All .ino files are smashed together into a single one by the IDE before compiling. If you want to use the 'static' keyword to achieve file-level scope control, you should only have one .ino file. All other source files should be .cpp. They will be compiled separately.
gfvalvo:
All .ino files are smashed together into a single one by the IDE before compiling. If you want to use the 'static' keyword to achieve file-level scope control, you should only have one .ino file. All other source files should be .cpp. They will be compiled separately.