|
| Program file global1.c | Program file global2.c |
|---|---|
void f4()
{
extern int x;
/* global var x is declared in scope */
x = 4; // Access x in file global2.c !!!
}
void f3()
{
x = 4; // *** Access error !
// x is not defined nor declared
}
extern int x; /* global var x is declared in scope */
void f2()
{
x = 4; // Access x in file global2.c !!!
}
|
void f1()
{
x = 4; // *** Access error !
// x is not defined nor declared
}
int x; /* global var x is defined HERE */
void f2()
{
x = 4; // OK
}
|
How to run the program:
|
|
This will make global variables accessible in every function in the program file !!!
|
| File 1: global4a.c | File 2: global4b.c |
|---|---|
|
|
#include <stdio.h>
static double x; // Definition of x
void func()
{
x = 12345; // x accessible here !
printf( "x = %lf\n", x );
}
|
When you compile these programs, you will get an error:
UNIX>> gcc -c global4a.c // No error
UNIX>> gcc -c global4b.c // No error
UNIX>> gcc global4a.o global4b.o // Error in linking loader phase
Undefined first referenced
symbol in file
x global4a.o
ld: fatal: Symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
|
Explanation:
|
Note: try this
|
How to run the program:
|
|
void func()
{
static double x; // x is accessible only
// WITHIN this function !!!
// (Just like a local variable !)
x = 12345; // x accessible here !
printf( "x = %lf\n", x );
}
|
|