Internal Linkage of C++ Static Storage Persistence --- Static Global Variables

1. Concept

When the static qualifier is used for a variable whose scope is the entire file, the linkage of the variable will be internal. In a multi-file program, the distinction between internal and external linkage makes sense. Variables with internal linkage can only be used in the file to which they belong; but regular external variables have external linkage, that is, they can be used in other files.
Thinking: What if you want to use the same name in other files to represent other variables?
In addition to using the extern keyword, you can also use static modifier variables to limit the scope of variables to files
2. Example code
file1.cpp
#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.

Guess you like

Origin blog.csdn.net/banzhuantuqiang/article/details/130912644