visibility of static function

Hello everyone,

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): http://www.c-programming-simple-steps.com/static-keyword-in-c.html

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();}

2. Header File

void staticTest (void);

3. Function File

#include "staticTest.h"

void staticTest(void)
{Serial.println(foo);}

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?

Thank you so much!

Is there a question?

1."statictest" does NOT use the static keyword

  1. The web site is wrong - forget it exists!

Mark

Mike777: Hello everyone,

your three files aren't adequately described to tell you what is happening... what is the Main file? what is the Function 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.

thanks a lot! That was a really great help!