C Language Static specific analysis

Source: Internet
Author: User

Google in the last three pages of C language static content, can find very little information. Whether it is a lengthy and unintelligible words, in the key position or skip, the learner is not very large. So. I have this blog post, the length of the family, the Internet on the integration of data classification, and hand-coded code verification.

C language code is organized in a file, in a source program in all source files, an external variable (note is not a local variable) or function can only be defined in a source program once, if there are repeated definitions, the compiler will error. Along with the mutual reference between the different source file variables and functions, and the independent relationship, the extern and Statickeyword are produced.

Below, the specific analysis of Statickeyword in the code when the three major types of use:

One. Static global variable

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

The. Text section saves the program binaries that the process runs, the. Data segment holds all of the initialized global variables for the process, and the. BSS segment holds the global variables that the process has not initialized (there are a lot of messy segments in other segments, not tables). 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 .

The storage location for static global variables and other global variables is no different, either in the. Data segment (initialized) or in the. BSS segment (uninitialized). However , it is only valid within the source file in which it is defined, and other source files cannot be interviewed . So, when the general global variable wears a static coat, it becomes the bride, has the heart to belong to, can only be defined its source file (groom) in the variable or function access.

Here are some examples of demo programs

File1.h such as the following:

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

We define a static global variable Hello in file1.c, for the function printstr in file1.c.

#include "file1.h" static char* hello = "Hello cobing!"; void Printstr () {printf ("%s\n", Hello);}

FILE2.C is the file where our main program resides. FILE2.C assumes that the reference hello will compile an error

#include "file1.h" int main () {printstr ();p rintf ("%s\n", hello); return 0;}

An error such as the following:

[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. )

Suppose we change the file2.c to the following form:

#include "file1.h" int main () {printstr (); return 0;}

The connection will be compiled successfully.

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

In the example above, the hello in file1.c is a static global variable. It can be called by PRINTSTR in the same file. However, it cannot be called by file2.c in different source files.

Two. Static local variable

Ordinary local variables are allocated on the stack space, and 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 dynamically allocated on the heap. But remember to release it when you're done with this heap space.

The static local variable is called a statically local variable . It has several differences from ordinary local variables such as the following:

1) location : Static local variables are placed in the global store by the compiler. Data (note: Not within the. BSS section.) Reason (see 3)), so although it is local, it exists throughout the lifetime of the program.

2) access permissions : Static local variables can only be interviewed by variables or functions within their scope.

That is, although it exists throughout the life of the program, because it is static, it cannot be interviewed by other functions and source files.

3) value : The static local variable assumption is not initialized by the user, then the compiler will voluntarily assign a value of 0. Each time a static local variable is called, the value after the last call is used.

This is a good understanding, each time the function calls the static local variable and then change it to leave, the next time you read from the global store read the static local variable is the last modified value.
Here are some examples of demo programs:

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

#include "file1.h" void Printstr () {int normal = 0;static int stat = 0;//this is a static local varprintf ("normal =%d---- Stat =%d\n ", normal, stat); normal++;stat++;}

For the sake of comparison, I have defined two variables: normal local variable normal and static local variable stat. They are all given an initial value of 0;

Call File1.h in file2.c:

#include "file1.h" int main () {printstr (); Printstr (); Printstr (); Printstr (); printf ("Call stat in Main:%d\n", stat); Retu RN 0;}

This call will cause an error, as the static local variable stat in file1.c is referenced in file2.c, such as the following:

[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 that stat is not declared, because it does not see the stat in file1.c to wager this line:

#include "file1.h" int main () {printstr ();p rintstr ();p rintstr ();p rintstr ();//printf ("Call stat in Main:%d\n", stat); return 0;}

[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
Do as you see above. It can be seen that the function is called every time. Common local variables are allocated again. 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 call may produce different results. This can be a potential hazard in multithreaded programming. Need to be more careful.


three, the static function
I believe you remember the private function in C + + object-oriented programming, where private functions only have access to member variables or member functions of that class.

In the C language, there is also "private function", which is the next static function, complete object-oriented programming in the function of the private function.

When you have very many source files in your program, you will certainly let a source file 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 a private function in object-oriented.

Here are some examples of demos:

File1.h such as the following:

#include <stdio.h>static int called (); void Printstr ();

File1.c such as the following:

#include "file1.h" static int called () {return 6;} void Printstr () {int returnval;returnval = called ();p rintf ("returnval=%d\n", ReturnVal);}

The two functions declared in File1.h are called in file2.c. Here we are useful to call called ():

#include "file1.h" int main () {int val;val = called ();p rintstr (); return 0;}

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
The function is not found in file2.c because it references the static function in File1.h: undefined reference to ' called '

The following changes file2.c:

#include "file1.h" int main () {printstr (); return 0;}

Compile execution:

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

The static function, which can solve the problem of different functions with the same name, is very good in the original document because the static function of the source file in other source files is not visible.

Hope you have a lot of supervision of the local wing ~ ~


C Language Static specific analysis

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.