1. Concept
#include <iostream>
int tom=3;
int harry=300;
void remote_access();
using namespace std;
int main()
{
cout <<"main() reports the following addressses:\n";
cout <<"file1.cpp &tom"<<&tom<<",,,,tom="<<tom<<endl;
cout <<"file1.cpp &harry"<<&harry<<",,,,harry="<<harry<<endl;
remote_access();
return 0;
}
file2.cpp
#include <iostream>
extern int tom;
static int harry=200;
void remote_access()
{
using namespace std;
cout << "remote_access() reports the follwing addresses:\n";
cout <<"file2.cpp &tom"<<&tom<<",,,,tom="<<tom<<endl;
cout <<"file2.cpp &harry"<<&harry<<",,,,harry="<<harry<<endl;
}
Compile the above two cpp files: g++ file1.cpp file2.cpp -o test
The execution results are as follows:
main() reports the following addressses:
file1.cpp &tom0x403010,,,,tom=3
file1.cpp &harry0x403014,,,,harry=300
remote_access() reports the follwing addresses:
file2.cpp &tom0x403010,,,,tom=3
file2.cpp &harry0x403020,,,,harry=200
Summary: The above description, use extern to achieve the effect of only one variable, follow the single variable rule, only define once, and the memory address is the same (the memory address of the tom variable in file1.cpp and the variable memory address in file2.cpp are the same) ;Using static to declare variables is equivalent to reapplying variables (the memory address of the harry variable in file1.cpp is not the same as the variable memory address in file2.cpp), the scope of this variable is in file2.cpp, that is, in this file, Single variable rules can also be achieved, the principle is similar to using namespace.