Compiling, linking and using c++ global variables

Time:2022-6-11

Global variables, in H document declaration.

1. Add extern to correspond CPP can be used, and other files containing this header can be used. However, if more than 2 files contain this header file, there will be a repeatedly defined link error.
    You can use namespace to solve this problem. Anonymous namespace is equivalent to compiling this obj to generate random scope names. Multiple files contain multiple random scopes. Therefore, anonymous namespace is generally not recommended.
    
2. No extern, only H can be used, corresponding to CPP is also not available.
    Although it is not available, you can still include this header file in multiple files. However, after it is included, multiple scopes, that is, multiple random scope names, will appear. A. CPP inclusion is random scope a, and b.cpp inclusion is random scope B. During operation, each one is used.
    Multi inclusion, you can still use namespace to solve the problem of repeated definitions.

Global variable Usage Summary:

1. Correct usage: The real name namespace+extern declaration in H corresponds to The variable definition with type in CPP can be initialized or not;
2、. H, no definition, no namespace, no extern This variable is not recognized directly in CPP, and compilation error occurs. Because there is no extern declaration, it is only limited to the availability of this document.
3、. H (initialization means definition). There is no problem with the inclusion of a single file and it can be used. In case of multiple inclusion, the link defined repeatedly is wrong.
4、. H uses anonymous namasapce with random scope. There is no problem with single file inclusion because only one scope is used. Multiple files contain multiple definitions in multiple scopes. It is very difficult to find out the mistakes.
5、. H uses the real name namespace instead of extern, multiple files contain, and there are still duplicate link errors;
6、. H, the real name namespace, does not use extend, only declares, does not define, in the corresponding When defining variables in CPP, there will be compilation errors: redefine;
7、. H, the real name namespace, using extend, is declared but not defined. Link error: there is no definition of this variable, which is also an external symbol that lnk2001: cannot resolve.

Brief summary:

If multiple files use variables, please use the real name namespace+extern declaration + definition;