A detailed analysis of static in C language

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/keyeagle/article/details/6708077

Google has nearly three pages of the C language of static content, found that the available information is very little, either long-winded or in the key point of a few words, for beginners who want to dig the underlying principle of the reference is not very large. So, this blog post to the people of the long, the Internet on the integration of data classification, and hand-written program verification.

C language code is organized in a file, in all source files of a source program, an external variable (note is not a local variable) or function can only be defined in one source program, if there is a duplicate definition, the compiler will error. The extern and static keywords are generated along with the mutual references between the different source file variables and functions, and the independent relationships.

The following is a detailed analysis of the three main types of use of the static keyword when writing programs:

one, the static global variable

We know that a process is shown in in-memory layout 1:

                    

The. Text section saves the program binaries that the process executes, the. Data segment holds all the initialized global variables of the process, and the. BSS section holds the global variables that the process is not initialized (there are many other segments in the other segment, not the table). During the entire life cycle of the process, the data in the. die and. BSS segments are the same as the entire process, which is the data that sanitization to sleep after the process has ended.

When a process's global variable is declared as static, its Chinese name is called a static global variable . There is no difference between static global variables and other global variables where they are stored, either in the. Data segment (initialized) or in the. BSS segment (uninitialized), but it is only valid within the source file that defines it, and other source files cannot access it . So, when the general global variable wears a static coat, it becomes the bride, which has the heart to belong to, can only be defined by its source file (groom) in the variable or function access.

Here are some sample programs:

File1.h as follows:

1 #include <stdio.h>  2   3void printstr ();  

We define a static global variable Hello in file1.c, which is accessed by the function printstr in file1.c.

1#include"File1.h"  2   3 Static Char* Hello ="Hello cobing!"; 4   5 voidprintstr ()6 {  7printf"%s\n", hello); 8}

FILE2.C is the file where our main program is located, file2.c if the reference hello will compile an error

1 " File1.h "  2   3 int Main ()   4 {  5    printstr ();   6     printf ("%s\n", hello);   7     return 0 ;   8

The error is as follows:

[Email protected] static]$ gcc-wall file2.c file1.c-o file2
file2.c:in function ' main ':
File2.c:6: Error: ' Hello ' is not declared (first use within this function)
File2.c:6: Error: (even if multiple occurrences occur within a function, each undeclared identifier is in its
File2.c:6: Error: Only one report is reported within the function. )

If we change file2.c to the following form:

1 " File1.h "  2   3 int Main ()   4 {  5    printstr ();   6     return 0 ;   7 }  

The connection will be compiled successfully.

The results after running the program are as follows:
[Email protected] static]$ gcc-wall file2.c file1.c-o file2
[Email protected] static]$./file2
Hello cobing!

In the above example, hello in file1.c is a static global variable that can be called by PRINTSTR in the same file, but not by file2.c in a different source file.

Second, static local variables

Ordinary local variables are allocated on the stack space, where the function of the local variable is called multiple times, and each time the local variable is called, the position on the stack is not necessarily the same. Local variables can also be allocated dynamically on the heap, but remember to release them when you are done with the heap space.

The static local variable is called a statically local variable . It differs from ordinary local variables in the following different aspects:

1) location : Static local variables are placed in the global store by the compiler. Data (note: Not within the. BSS section for reasons 3)), so it is local, but exists throughout the program's life cycle.

2) access rights : Static local variables can only be accessed by variables or functions within their scope. This means that although it will exist throughout the life of the program, because it is static, it cannot be accessed by other functions and source files.

3) value : If the static local variable is not initialized by the user, it is automatically assigned a value of 0 by the compiler, and the last call value is used each time the static local variable is called. This is a good understanding, each time the function calls static local variables are modified and then left, the next time you read from the global store read the static local variable is the last modified value.
Here are some sample programs:

The contents of File1.h are the same as in the previous example, and the contents of file1.c are as follows:

1#include"File1.h"  2   3 voidprintstr ()4 {  5     intnormal =0; 6     Static intStat =0;//This is a static local var7printf"normal =%d----stat =%d\n", Normal, stat); 8normal++; 9stat++; Ten}

For comparison purposes, I have defined two variables: normal local variable normal and static local variable stat, which are given an initial value of 0;

Call File1.h in file2.c:

1#include"File1.h"  2   3 intMain ()4 {  5 Printstr (); 6 Printstr (); 7 Printstr (); 8 Printstr (); 9printf"Call stat in main:%d\n", stat); Ten     return 0;  One}

This call will error because the static local variable stat in file2.c is referenced in file1.c as follows:

[Email protected] static]$ gcc-wall file2.c file1.c-o file2
file2.c:in function ' main ':
File2.c:9: Error: ' stat ' not declared (first use within this function)
File2.c:9: Error: (even if multiple occurrences occur within a function, each undeclared identifier is in its
File2.c:9: Error: Only one report is reported within the function. )

The compiler says stat is not declared, because it does not see the stat in file1.c, and the following is the line:

1#include"File1.h"  2   3 intMain ()4 {  5 Printstr (); 6 Printstr (); 7 Printstr (); 8 Printstr (); 9 //printf ("Call stat in Main:%d\n", stat); Ten     return 0;  One}

[Email protected] static]$ gcc-wall file2.c file1.c-o file2
[Email protected] static]$./file2
normal = 0----Stat = 0
normal = 0----Stat = 1
normal = 0----Stat = 2
normal = 0----stat = 3

Run as shown above. As you can see, each time the function is called, the normal local variable is reassigned, while the static local variable keeps the value of the last call unchanged.

It is important to note that because of this characteristic of the static local variable, the function that contains the static local variable becomes non-reentrant, that is, each invocation may produce different results. This can be a potential hazard in multithreaded programming. Need to be careful.


third, the static function
I believe you will remember the private function in C + + object-oriented programming, and only the member variables or member functions of the class can be accessed. In the C language, there is also "private function", which is the next static function to complete the object-oriented programming of the function of the private function.

When you have a lot of source files in your program, you will certainly let a source file to provide only some external interfaces, other functions may be written to implement these interfaces, these other functions you may not want to be seen by the outside (non-source file), this time you can use static to modify these " Other functions. "

so the scope of the static function is the source file, think of it as an object-oriented private function can be.

Here are some examples:

File1.h as follows:

1 #include <stdio.h>  2   3staticint  called ();   4 void printstr ();  

File1.c as follows:

1#include"File1.h"  2   3 Static intcalled ()4 {  5     return 6; 6 }  7 voidprintstr ()8 {  9     intReturnVal; TenReturnVal =called ();  Oneprintf"returnval=%d\n", ReturnVal);  A}

FILE2.C calls the two functions declared in File1.h, where we deliberately invoke called ();

1 " File1.h "  2   3 int Main ()   4 {  5     int  val;   6     val = called ();   7     printstr ();   8     return 0 ;   9 }

The error will be at compile time:

[Email protected] static]$ gcc-wall file2.c file1.c-o file2
File1.h:3: Warning: ' called ' has been used but never defined
/tmp/ccylubzu.o:in function ' main ':
FILE2.C: (. text+0x12): Undefined reference to ' called '
COLLECT2:LD return 1
This function is not found in file2.c because it references the static function in File1.h: undefined reference to ' called '

Modify FILE2.C below:

1 " File1.h "  2   3 int Main ()   4 {  5    printstr ();   6     return 0 ;   7 }

Compile run:

[Email protected] static]$ gcc-wall file2.c file1.c-o file2
[Email protected] static]$./file2
Returnval=6

The static function solves the problem of the same name in different original files, because one source file is not visible to the static functions in other source files.

There is an omission of the place to look at you more advice ~ ~

A detailed analysis of static in C language

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.