View previous topic :: View next topic |
Author |
Message |
Franck26
Joined: 29 Dec 2007 Posts: 122 Location: Ireland
|
Static variable become global??? |
Posted: Thu Mar 20, 2008 5:59 am |
|
|
Hello,
I don't know if my definition of a static variable is correct or not, but for me a static variable which is declared on a .c file is not accessible by the other .c files...
Am I right?
My problem is that I have declared a static variable at the top of a .c file (not inside a function) and it seems that my others .c files are able to access to this variable...
Is it normal?
example:
main.c:
Code: | #include <main.h>
#include <File1.c>
#include <File2.c>
void main()
{
while(1)
{
ChangeVariable();
}
} |
file1.c:
Code: | static unsigned int Penguin; |
file2.c:
Code: | void ChangeVariable(void)
{
Penguin = 12;
} |
When I do that there is no error and the variable Penguin is load with 12.
If in the main.c I include first file2.c and file1.c, the Penguin variable is not found and an error is generated. (which is normal).
Compiler: PCD 4.069.
Thanks for any comments.
Franck. |
|
|
Ttelmah Guest
|
|
Posted: Thu Mar 20, 2008 6:11 am |
|
|
Nothing to do with being static.
In C, any variable, that is declared _outside_ of any function, _is_ global. Declare your static variables, inside function declarations, and they become local static variables.
This is standard C syntax.
Remember 'include' files, are not separate programs. They are simply treated as if they are typed in at the point they are loaded.
Best Wishes |
|
|
gribas
Joined: 21 Feb 2008 Posts: 21
|
|
Posted: Thu Mar 20, 2008 6:51 am |
|
|
Hi Franck26,
The 'static' keyword isolates global variables from different compilation units. It also prevents a local function variable from being initialized twice.
I guess you only have one compilation unit. Use #module to achieve what you want. |
|
|
Franck26
Joined: 29 Dec 2007 Posts: 122 Location: Ireland
|
|
Posted: Thu Mar 20, 2008 8:01 am |
|
|
Hi,
Thanks for your answer.
I understand now: till now I was always working with several compilation units, but since I am using CCS, I was not able to do it...
I've tried the #module, it's working fine.
Thanks a lot.
Franck. |
|
|
|