C++ learning record-extern, static, declaration and definition, global variables and local variables

  • The difference between local variables and global variables
  1. Local variables are defined inside a function and are not accessible outside the function. (Defined in an area limited by {})
  2. Global variables are defined outside all functions, and all functions within their scope can be accessed. Let's explain in detail below.
  3. The lifetime of a local variable is in the {} where it is defined. A global variable is any variable defined in the program except for all functions (including the main function).
  4. The scope of global variables is the part of the program from the variable definition to the end of the entire program. This means that global variables can be accessed by all functions defined after the global variables.
#include<iostream>
using namespace std;
void California (); // Function prototype

int BIRDS = 500; // Global constant
int main()
{
    
    
    cout <<  "In main there are " << BIRDS << " birds.\n";
    California();
    cout <<  "In main there are " << BIRDS << " birds.\n";
    return 0;
}

void California()
{
    
    
    const int BIRDS = 10000;
    cout << "In California there are " << BIRDS << " birds.\n";
}

输出:
In main there are 500 birds.
In California there are 10000 birds.
In main there are 500 birds.

From the above, let us temporarily understand the local variables and global variables.

  • The difference between declaration and definition in C++

"C++Primer" fourth edition section 2.3.5 said this:

  1. Variable definition: It is used to allocate storage space for variables, and can also specify initial values ​​for variables. In the program, the variable has one and only one definition. But there can be multiple declarations
  2. Variable declaration: used to indicate the type and name of the variable to the program.
  3. A definition is also a declaration: when we define a variable we declare its type and name.
  4. externKeywords: externDeclare variable names by using keywords without defining it.
extern int i;// 是声明,不是定义,也即不分配空间。
int i;// 是声明,同时也定义,为其分配了空间。
任何包含了显式初始化的声明即成为定义。
我们能给由extern关键字标记的变量赋一个初始值,但是这么做也就抵消了extern的作用。extern语句如果包含初始值就不再是声明,而变成定义了:
extern int i = 10;//定义,extern作用被抵消

函数的声明和定义区分比较简单,带有{
    
    }的即为定义,没带{
    
    }即为声明。
int max(int a, int b); //函数的声明

Give an example to illustrate that there is only one definition, but there can be multiple declarations

#include<iostream>
using namespace std;
extern int a;//声明
int main(){
    
    
	int a = 10;//定义
	int a = 11;//此时,编译器会报错。
	a = 11;//此时,并不会报错,这不在是定义了,而是赋值。
	cout << a << endl;
	return 0;
}
  1. hide. (Static function and static variable are both)
    When compiling multiple files at the same time, all global variables and functions that are not prefixed with static have global visibility.
    Give an example to illustrate. Compile two source files at the same time, one is ac and the other is main.c.
//a.c
char a = 'A'; // global variable
void msg()
{
    
    
     printf("Hello\n");
}
 
//main.c
 
int main()
{
    
    
     extern char a; // extern variable must be declared before use
     printf("%c ", a);
     (void)msg();
     return 0;
}
输出:
Hello

Why can the global variables aand functions defined in ac be used in ac ? msgmain.c
All staticunprefixed global variables and functions have global visibility, and other source files can also be accessed. In this example, it ais a global variable, msga function, and there is no staticprefix, so it is visible to the other source file main.c.
If it is added static, it will be hidden from other source files. For example , if you add before the definition of aand msg static, you can't see them in main.c. Use this feature to define functions and variables with the same name in different files without worrying about naming conflicts. staticIt can be used as a prefix for functions and variables. For functions, staticthe function is limited to hiding.

  1. staticThe second role is to keep the variable content persistent. ( staticMemory function and global lifetime in variables)

The variables stored in the static data area will be initialized at the beginning of the program, which is the only initialization. There are two kinds of variables stored in the static storage area: global variables and static variables, but compared with global variables, staticyou can control the visible range of variables. After all, static is used to hide. Although this usage is not common
PS: if staticit is defined as a local variable in a function, its lifetime is the entire source program, but its scope is still the same as an automatic variable, and the variable can only be used in the function that defines the variable. After exiting the function, although the variable still exists, it cannot be used.

#include <stdio.h>
 
int fun(){
    
    
    static int count = 10; //在第一次进入这个函数的时候,变量a被初始化为10!并接着自减1,以后每次进入该函数,a
    return count--; //就不会被再次初始化了,仅进行自减1的操作;在static发明前,要达到同样的功能,则只能使用全局变量:    
 
}
 
int count = 1;
 
int main(void)
{
    
    
     printf("global\t\tlocal static\n");
     for(; count <= 10; ++count)
               printf("%d\t\t%d\n", count, fun());
     return 0;
}
输出:
global  local static
1 10
2 9
3 8
4 7
5 6
6 5
7 4
8 3
9 2
10 1

-Based on the above two points, a conclusion can be drawn: changing a local variable to a static variable changes its storage mode, that is, changes its lifetime. Changing a global variable to a static variable changes its scope and limits its scope of use. Therefore static, the role of this specifier in different places is different.

  1. staticThe third role is to initialize to 0 by default ( staticvariable)

In fact, global variables also have this attribute, because global variables are also stored in the static data area. In the static data area, the default value of all bytes in the memory is · 0x00, this feature can reduce the programmer's workload in some cases. For example, to initialize a sparse matrix, we can put all the elements one by one 0, and then 0assign values ​​to several elements that are not . If it is defined as static, the initial setting 0operation is omitted . Another example is to use a character array as a string, but I think it is ‘\0’too troublesome to add at the end of the character array every time . If the string is defined as static, this trouble will be saved, because it is originally there ‘\0’; you might as well do a little experiment to verify it.

#include <stdio.h>
 
int a;
 
int main()
{
    
    
     int i;
     static char str[10];
     printf("integer: %d; string: (begin)%s(end)", a, str);
     return 0;
}
输出:
integer: 0; string: (begin) (end) 

Finally static, make a one-sentence summary of the three functions. First of all, the main function of static is to hide, and secondly, because the staticvariable is stored in the static storage area, it has persistence and default value 0.

  1. static Role in the class

To be continued-
for reference, not yet seen-the role of static in the class
for reference, not yet seen-the difference between static and const

  • extern Function summary

In the C language, modifiers are externused before the declaration of a variable or function to indicate that "this variable/function is defined elsewhere and should be quoted here." When externdeclaring a global variable, you should first make it clear: externthe scope is the entire project, that is, when we write it in the .h file extern int a; when linking, the linker will go to other .cpp files to find out if there is any int aIf not, the link will report an error;

  1. externModified variable declaration

If the file ac needs to refer to the variables in bc int v, it can be declared in ac extern int v, and then the variables can be referenced v.
It should be noted here that the vlink attribute of the referenced variable must be external, which means that ac must be referenced v, not only depends on the declaration in ac extern int v, but also depends on the variable vitself being able to be referenced .
This involves another topic of the C language-the scope of variables. externVariables that can be referenced by other modules with modifiers are usually global variables.
Another very important point is that extern int vcan be placed anywhere in the ac, for example, you can ac function in the funbeginning of the declaration at the definition extern int v, then you can refer to variables v, and only in this way can only function funreference scope vForget it, this is still a question of variable scope. For this, many people have concerns when using it. It seems externthat the declaration can only be used at file scope.

shengming.h

extern int a;
extern int b;

shengming.cpp //此处并不需要加 #include ”shengming.h"

int a = 10;
int b = 20;

main.cpp

#include <iostream>
#include "shengming.h"
using namespace std;
int main()
{
    
    
    cout << a << " " << b << endl;
    return 0;
}
输出: 10 20
  1. externModified function declaration

In essence, there is no difference between a variable and a function. The function name is a pointer to the beginning of the binary block of the function.
If you need to refer to the file ac bc in function, such as in the prototype bc int fun(int mu), it can be declared in ac extern int fun(int mu), then you can use funto do anything.
Just like the declaration of a variable, it extern int fun(int mu)can be placed anywhere in ac, not necessarily in the scope of the file scope of ac.
For references to functions in other modules, the most common method is to include the header files of these function declarations. Use externand include the header file to reference what difference does it function?
externThe way of quoting is much more concise than including header files! externThe method of using is straightforward. You can externdeclare which function you want to refer to .
One obvious advantage of this is that it will speed up the process of program compilation (preprocessing, to be precise) and save time. In the process of compiling large C programs, this difference is very obvious.

  1. externModifiers can be used to indicate the calling specification of C or C++ functions

For example, calling the C library functions in C ++, you need to program in C ++ using extern “C”statement to reference the function.

This is for the linker, telling the linker to use the C function specification to link when linking. The main reason is that C++ and C programs have different naming rules in the target code after they are compiled.
References-Using extern to compile C and C++ mixed

  • The difference between extern and static modified global variables

The static keyword has many functions, such as declaring static global variables, static local variables, and static members of classes. The main discussion here is the difference between him and extern when modifying global variables. There are two points to note:
1. When static modifies global variables, the declaration and definition are given at the same time;
2. The global scope of static is only its own compilation unit. extern refers to the entire project. A compilation unit refers to a .cpp file and the header files it contains. That is to say, when static modifies global variables, the scope of "global" is smaller than extern. Therefore, using static to declare (and define) global variables in the header file will not have the problem of repeated definitions discussed above.
Refer to the difference between extern and static to modify global variables

If extern wants to access other files modified as static variables, it is not allowed. extern is not a definition, but the introduction (declaration) of non-static global variables defined in other source files;

Unread references

Guess you like

Origin blog.csdn.net/JACKSONMHLK/article/details/114236757