External linkage of C++ static persistence --- ordinary member variables, variable single definition rules and extern usage examples

1. Single definition rule

C++ has " Single Definition Rule " ( One Definition Rule , ODR ), which states that,
A variable can only be defined once. To meet this need, C++ provides two variable declarations. one
One is a defining declaration (definition), which allocates storage space to variables; the other is a referencing declaration (or simply a declaration), which does not allocate storage space to variables, because It refers to an existing variable.
A reference declaration uses the keyword extern and does not initialize
Note: If multiple identical variable names exist in a program at the same time, an error will be reported when compiling. At this time, the following methods can be used to avoid:
1. Use the extern keyword
2. Use the namespace namespace
3. Use static to modify the variable, the static qualifier makes the variable limited to this file, and overwrites the corresponding global definition (that is, the variable modified with static is an internal link, the principle is similar to 2, and the scope is limited)

2. Example of use

file1.cpp

#include <iostream>
int tom=3;

using namespace std;

int main()
{
    cout <<"file1.cpp &tom"<<&tom<<",,,,tom="<<tom<<endl;
    remote_access();
   cout <<"file1.cpp &tom"<<&tom<<",,,,tom="<<tom<<endl;
    return 0;
}

file2.cpp

#include <iostream>
extern int tom;
//extern int tom=5;//这里这样重新初始化编译会报错
//static int tom=4; //使用static修饰的变量,具有内部链接性,该变量限制在file2.cpp中使用,也可行


void remote_access()
{
    using namespace std;
    tom=5;//这样重新赋值可以,而且file1.cpp的tom变量值也被修改成了5
 
    cout <<"file2.cpp &tom"<<&tom<<",,,,tom="<<tom<<endl;
}

Compile the above two files, g++ file1.cpp file2.cpp -o test

The program execution results are as follows:

file1.cpp &tom0x403010,,,,tom=3
remote_access() reports the follwing addresses:
file2.cpp &tom0x403010,,,,tom=5
file1.cpp &tom0x403010,,,,tom=5

Guess you like

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