Hello everybody!
I'm trying to understand static variables.
I have these files:
main.c
Code:
#include <stdio.h>
#include <stdlib.h>
#include "example.h"
int main()
{
int a=2;
return 0;
}
example.h
example.c
Code:
int a=1;
void func()
{
...}
In this case, example.c contains the var a (not static) and so main.c can see it and forbids the creation of a new variable with the same name, by giving the error:
obj\Debug\main.o:main.c: (.data+0x0): multiple definition of `a'
obj\Debug\example.o:example.c: (.data+0x0): first defined here
If I edit the file example.c as follows:
Code:
static int a=1;
void func()
{
...
}
It doesn't give any error anymore because the variable inside example.c is "private", that is its scope is the file example.c.
But, if I remove the static keyword, the variable should be visible within main.c, so if I do something like this:
main.c
Code:
#include <stdio.h>
#include <stdlib.h>
#include "example.h"
int main()
{
printf("%d",a);
return 0;
}
It says me that a is undeclared.
main.c|7|error: 'a' undeclared (first use in this function)|
So doesn't it see it? If yes, why can't I create a variable with the same name? Or, better, why can't I reassign it? Because if I do something like this it works:
example.c
Code:
int a=1;
void func()
{
...
}
main.c
Code:
#include <stdio.h>
#include <stdlib.h>
#include "example.h"
int a;
//a=3; -> error!
int main()
{
printf("%d",a); //shows 1
return 0;
}