|
The scoping rules (that we just learned) will determine which function(s) will be able to access a variable
|
Therefore:
|
|
|
Because when the static global variables are defined at the top:
|
|
|
|
|
There is an easier way to declare global variables which I will dicuss next
|
Example:
|
Even though the global variable x is defined and declared in the program file p1.c, there is no error as long as the declaration and definition do not conflict.
The same is true for the global variable y in the program file p2.c
|
glob2.c:
int a, b;
float c, d;
void print()
{
printf( "print( )>>> a = %d, b = %d\n", a, b);
printf( "print( )>>> c = %f, d = %f\n", c, d);
}
|
glob1.c:
int main( int argc, char *argv[] )
{
a = 2;
b = 3;
printf( "a = %d, b = %d\n", a, b);
c = 2.0;
d = 3.0;
printf( "c = %f, d = %f\n", c, d);
print( ); // Calls print( ) in glob2.c
}
|
Then:
|
We will study how to declare global variables next....
extern DataType varName ;
|
| File: glob1.c | File: glob2.c |
|---|---|
extern int a, b;
extern float c, d;
int main( int argc, char *argv[] )
{
a = 2;
b = 3;
printf( "a = %d, b = %d\n", a, b);
c = 2.0;
d = 3.0;
printf( "c = %f, d = %f\n", c, d);
print( ); // Calls print( ) in glob2.c
}
|
int a, b;
float c, d;
void print()
{
printf( "print( )> a = %d, b = %d\n", a, b);
printf( "print( )> c = %f, d = %f\n", c, d);
}
|
Demo:
cd /home/cs255000/demo/c/multiple-files
gcc -c glob1.c
gcc -c glob2.c
gcc glob1.o glob2.o
a.out
a = 2, b = 3
c = 2.000000, d = 3.000000
print( )>>> a = 2, b = 3
print( )>>> c = 2.000000, d = 3.000000
|
|
But we have a C-preprocessor trick to make thing easy !!!!!