Detailed explanation and usage of Static keyword in C language

1. Executable program memory allocation

1. Executable Program Segmentation

Three basic segments of a program: text segment, data segment, bss segment

  1. BSS BSS (Block Started by Symbol) usually refers to a memory area used to store uninitialized global variables and static variables in the program.

        The characteristics are: readable and writable, the BSS segment will be automatically cleared to 0 before the program is executed.

        Therefore, uninitialized global variables have become 0 before the program is executed.

        Note the difference from the data segment. BSS stores uninitialized global variables and static variables, and the data segment stores initialized global variables and static variables.

Under UNIX, you can use the size command to view the segment size information of the executable file. Such as size a.out.

        2. The data segment .data stores data that can be determined during the compilation phase (rather than runtime), and is readable and writable.

        It is also commonly referred to as the static storage area. Global variables assigned initial values ​​and static variables assigned initial values ​​are stored in this area, and constants also exist in this area. The data segment and the code segment are determined before the program runs.

        3. Code segment. text The code segment usually refers to a memory area used to store program execution code.

        The size of this part of the area has been determined before the program runs, and the memory area is usually read-only, and some architectures also allow the code segment to be writable, which allows self-modifying programs.

        In the code segment, it is also possible to contain some read-only constant variables, such as string constants, etc.

        The text segment is determined at compile time, and is mapped as read-only in memory, but the date segment and bss segment are writable.

2. C language five major memory partitions

  1. Stack area (stack area stack)

        The stack is automatically allocated and released by the compiler to store function parameters and local variable values ​​(auto type), and the operation method is similar to the stack in the data structure. The application for the stack is automatically allocated by the system, such as applying for a local variable int h inside the function, and at the same time judge whether the requested space is smaller than the remaining space of the stack, if it is smaller, open up space for it, and provide memory for the program, otherwise an exception will be reported stack overflow.

        2. Heap

        The heap is generally allocated and released by the programmer. If the programmer does not release it, the program may be reclaimed by the OS at the end of the program.

        It is different from the heap in the data structure. The allocation method is similar to a linked list, and the application is operated by the programmer himself using malloc or new.

        The application process is relatively complicated. When the system receives an application from a program, it will traverse the linked list recording the free memory address in order to find the first heap node whose space is larger than the requested space, and then delete the node from the free node linked list, and Allocate the space of this node to the program. In some cases, the first address of the newly applied memory block records the size of the memory block allocated this time, so that the memory space can be released correctly during free().

        3. Global static storage area

        Global variables and static variables are stored together. Initialized global variables and static variables are stored in one area, and uninitialized global variables and uninitialized static variables are stored in another adjacent area.

        4. Literal constant area

        The constant string is placed in this part, the read-only storage area, and will be released by the system after the program ends

        5. Program code area

        Stores the binary code area of ​​the program.

        The difference between the two is: the code segment, data segment, and stack segment are cpu-level concepts, and the five major partitions belong to the language-level concept, and the two are different concepts.

3. Mapping and division of executable program memory space and logical address space

        The left side is the execution file of the UNIX system, and the right side is the division of the logical address space corresponding to the process

4. Example

Two, static variables

        Static variables mainly distinguish between static global variables and global variables, local variables and static local variables.

1. Static global variables, global variables

The difference between static global variables and global variables is mainly distinguished by life cycle and scope .

global variable static global variable
life cycle The program runs to the end of the program Program run start to program end
scope all codes Only the current file can be accessed
position in the code snippet global data area global data area
  • a. Static global variables and global variables are stored in the data segment .data;

  • b. A static local variable is defined within a function, and its lifetime is the entire source program, but its scope is the same as that of an automatic variable, and it can only be used within the function that defines the variable. After exiting the function, although the variable still exists, it cannot be used.

  • c. If the initial value is not assigned to the static local variable of the basic type when it is explained, the system will automatically assign a value of 0. However, if the initial value is not assigned to the automatic variable, its value is uncertain.

  • d. The global variable itself is a static storage method, and of course the static global variable is also a static storage method. But their scope, the scope of non-static global variables is the entire source program (multiple source files can be used together); while static global variables limit their scope, that is, they are only valid in the source file where the variable is defined, It cannot be used in other source files of the same source program.

global variable instance

The following are bc and ac source code

global variable

compile

gcc a.c b.c

Results of the:

Results of the

It can be seen from the compilation result that the file ac can access the static global variable b in the bc file.

Static global variable instance

compile result

compile result

It can be seen from the compilation result that the file ac cannot access the static global variable b in the bc file, so the compilation reports an error.

2. Static local variables, local variables

        The difference between static local variables and local variables is mainly distinguished by life cycle and scope .

local variable static local variable
life cycle function call to function return Program run start to program end
scope inside the function inside the function
position in the code snippet the stack global data area

        Static local variables are stored in the data segment .data, and local variables are on the stack; both static local variables and local variables can only be accessed inside the function body.

        A static local variable accessed by the function each time, the value of the variable is the modified value of the last access.

Example:

  1 #include <stdio.h>
  2 
  3 
  4 void func()
  5 {
  6     int aa = 11;
  7 
  8     printf("aa= %d \n",aa++);
  9 
 10 }
 11 
 12 int main(int argc, char **argv)
 13 {
 14 
 15     func();                                                                                    
 16     func();
 17 
 18     return 0;
 19 }

        For ordinary local variables, each time it is called, it will be initialized once on the stack.

 1 #include <stdio.h>
  2 
  3 
  4 void func()
  5 {
  6     static int aa = 11;
  7                                                                                                
  8     printf("aa= %d \n",aa++);
  9 
 10 }
 11 
 12 int main(int argc, char **argv)
 13 {
 14     
 15     func();
 16     func();
 17 
 18     return 0;
 19 }

        The static variable aa in the function is only initialized once, and the value accessed each time should be the last processed result of the last call to the function.

Three, static function

1. Concept:

        Add the keyword static before the return type of the function, and the function is defined as a static function.

        The definition and declaration of a function are extern by default, but a static function is only visible in the file where it is declared and cannot be used by other files.

        Static functions (also called internal functions) can only be called by functions in this file, but not by functions in other files of the same program.

        Different from general non-static functions (external functions), static can be used to modify variables in c, and can also be used to modify functions.

        First look at when it is used to modify variables. Variables in c can be divided into global data area, stack and heap.

        In fact, the stack we usually refer to is the stack and does not include the heap, so don't confuse it.

2. The benefits of defining static functions:

  • <1> Functions with the same name can be defined in other files, and there will be no conflicts. Don't worry about whether the functions you define will have the same name as functions in other files, because the same name does not matter.

  • <2> Static functions cannot be used by other files. The storage specifiers auto, register, extern, and static correspond to two storage periods: automatic storage period and static storage period.

  • <3> The count function declares a local variable of the function and sets it as a static type as a counter, so that the function can be counted every time it is called. This is the best way to count the number of times a function is called, because this variable is closely related to the function, and the function may be called in many different places, so it is difficult to count from the perspective of the caller.

  • <4> The static function will be automatically allocated in a storage area that has been used until the application instance is exited, which avoids pushing and popping the stack when calling the function, and the speed is much faster.

example

a.c

  1 #include <stdio.h>
  2 
  3 void func();
  4 
  5 int main(int argc, char **argv)
  6 {
  7     
  8     func();                                                                                                        
  9 
 10     return 0;
 11 }

b.c

  1 #include <stdio.h>
  2 
  3 int b = 10;
  4 
  5 
  6 static void func()                                                                                                 
  7 {
  8     printf("in func b =%d\n",b);
  9 }

compile

It can be seen from the compilation result that file a cannot access the static function func in file b.

Guess you like

Origin blog.csdn.net/huanxiajioabu/article/details/131458177
Recommended