// file1.C
#include <iostream.h>
int x;
int main()
{
x = 1234;
cout << x << endl;
f();
cout << x << endl;
}
|
// file2.C
#include <iostream.h>
void f()
{
x = 9999;
}
|
The compile cannot complete its job because it does NOT know the LOCATION, TYPE and SIZE about the variable
Compile with:
// file1.C
#include <iostream.h>
int x;
int main()
{
x = 1234;
cout << x << endl;
f();
cout << x << endl;
}
|
// file2.C
#include <iostream.h>
int x;
void f()
{
x = 9999;
}
|
It will work when compile with the Solaris C++ compile :
And it will fail to compile with the GNU C++ compile :
// file1.C
#include <iostream.h>
int x;
int main()
{
x = 1234;
cout << x << endl;
f();
cout << x << endl;
}
|
// file2.C
#include <iostream.h>
void f()
{
x = 9999;
// Compiler does not know
// address, type and size of x
}
|
Example variable definition:
int myVar; float yourVar; |
Example variable DECLARATION:
extern int myVar; extern float yourVar; |
Important fact:
| A declaration DOES NOT reserve any memory space (for the variable). |
| To provide the C/C++ compiler with the necessary information of the variable so that it CAN manipulate/use the variable) |
Program file 1
int myVar; // DEFINITION
float yourVar; // DEFINITION
int main(int argc, char *argv[])
{
....
}
|
Program file 2
extern int myVar; // DECLARATION
extern float yourVar; // DECLARATION
int AnotherFunction(....)
{
yourVar = myVar + sin(2.3);
....
}
|
It will work when compile with the Solaris C++ compile :
And it will ALOS work to compile with the GNU C++ compile :
// Header file vars.h int x; int y; .... |
// Program file 1 #include "vars.h" .... |
// Program file 2 #include "vars.h" .... |
is to use the " #define EXTERN " trick
// Header file vars.h #ifndef EXTERN #define EXTERN extern #endif EXTERN int x; EXTERN int y; .... |
// Program file 1 #define EXTERN #include "vars.h" .... main() .... |
// Program file 2 #include "vars.h" .... |
After preprocessing the EXTERN definition:
// Header file vars.h #ifndef EXTERN #define EXTERN extern #endif EXTERN int x; EXTERN int y; .... |
// Program file 1 int x; int y; .... main() .... |
// Program file 2 extern int x; extern int y; .... |