Results 1 to 8 of 8
I have one doubt..
a.h
static int x;
1.c
#include"a.h"
x=10;
printf("x=%d",x);
2.c
#include"a.h"
x=200;
printf("x=%d",x);
2.c
#include"a.h"
x=x+1;
printf("x=%d",x);
In the above said files static int is delcared in ...
- 06-27-2010 #1Just Joined!
- Join Date
- Nov 2006
- Location
- Hyderabad
- Posts
- 85
static violation
I have one doubt..
a.h
static int x;
1.c
#include"a.h"
x=10;
printf("x=%d",x);
2.c
#include"a.h"
x=200;
printf("x=%d",x);
2.c
#include"a.h"
x=x+1;
printf("x=%d",x);
In the above said files static int is delcared in a.h file.this file is included in all 1.c , 2.c 3.c files.And able to compile the code & run it successfully.
But here my question is::
static is local to a.h file,,,but how we are to able access it..Is this static varibale access violation?
- 06-27-2010 #2
Hi,
"static" was a poor choice for a name in the C standard for this. In this context, it does not mean "unflexible", "constant" or "write-protected". A better choice would have been "local".
Instead it means: Let each "translation unit" have its own variable x. (A translation unit is a .c file together with all .h files it includes.)Debian GNU/Linux -- You know you want it.
- 06-27-2010 #3
I don't see your source file where you declare the static variable....
a.c
To compile the aboveCode:static int x = 0;
gcc -c a.c
And to compile one of your executables
gcc 1.c a.o -o thefirstone
How does this compile?
Oops, modifying 1.c to the below
1.c
I think including a header file with the static declaration includes the static declaration in the main executable...I think.Code:#include <stdio.h> extern int x; int main(int argc, char**argv) { x = 1234; return 0; }Last edited by gerard4143; 06-27-2010 at 01:35 PM.
Make mine Arch Linux
- 06-27-2010 #4Just Joined!
- Join Date
- Nov 2006
- Location
- Hyderabad
- Posts
- 85
No no...
static int x;
is declared in a.h header file.
#gcc 1.c 2.c 3.c
- 06-27-2010 #5
- 06-27-2010 #6
The result of including a.h is below:
Which is a valid C program.Code:#include <stdio.h> static int x;/*the result of including a.h is this line*/ int main(int argc, char**argv) { x = 789; fprintf(stdout, "x->%d\n", x); return 0; }Make mine Arch Linux
- 06-28-2010 #7
gerard4143 is correct. When you run #include FILE, you are actually copying the entire contents of that file into your file. In this instance, each of your .c files has declared its own static int x.
Header files are designed to be included in the source code files. The source code files are designed to define all of the functionality (not always true when using macros, for instance, but usually true).DISTRO=Arch
Registered Linux User #388732
- 06-28-2010 #8Just Joined!
- Join Date
- Nov 2006
- Location
- Hyderabad
- Posts
- 85
Yeah that's correct,
Thank you for information.....


Reply With Quote
