Detailed static analysis in C Language

Source: Internet
Author: User

C LanguageCodeIs organized in the unit of files, in a sourceProgramIn all source files, an external variable (not a local variable) or function can only be defined once in a source program. If there is a repeated definition, the compiler will report an error. The extern and static keywords are generated along with the mutual reference and independent relationship between different source file variables and functions.

Next, we will analyze the usage of static keywords in three categories during programming:

1. Static global variables

We know that the layout of a process in the memory is as follows:

Where. text to save the program binary file executed by the process ,. the data segment stores all initialized global variables of the process ,. the BSS segment stores the uninitialized global variables of the process (there are many messy segments in other segments, which are not listed at the moment ). During the entire lifecycle of a process, data in the. Data Segment and the. BSS segment coexist with the entire process, that is, after the process ends, the data will end up.

When a process's global variable is declared as static, its Chinese name isStatic global variables. Static global variables and other global variables are stored in the. Data Segment (initialized) or. BSS segment (not initialized),It is only valid in the source file defining it, and other source files cannot access it.. Therefore, when a common global variable is put on the static coat, it becomes a bride and can only be accessed by variables or functions in its source file (groom.

Below are some sample programs

File1.h is as follows:

    1. # Include <stdio. h>
    2. VoidPrintstr ();

We define a static global variable hello in file1.c for the function printstr in file1.c to access.

    1. # Include "file1.h"
    2. Static Char* Hello ="Hello cobing! ";
    3. VoidPrintstr ()
    4. {
    5. Printf ("% S \ n", Hello );
    6. }

File2.c is the file where our main program is located. If Hello is referenced in file2.c, an error occurs during compilation.

    1. # Include "file1.h"
    2. IntMain ()
    3. {
    4. Printstr ();
    5. Printf ("% S \ n", Hello );
    6. Return0;
    7. }

The following error is reported:

[Liujx @ server235 static] $ gcc-wall file2.c file1.c-O file2
File2.c: In function 'main ':
File2.c: 6: Error: 'Hello' is not declared (used for the first time in this function)
File2.c: 6: Error: (even if it appears multiple times in a function, each undeclared identifier
File2.c: 6: Error: only one report is reported in the function .)

If we change file2.c to the following format:

    1. # Include "file1.h"
    2. IntMain ()
    3. {
    4. Printstr ();
    5. Return0;
    6. }

The connection will be compiled smoothly.

The result of running the program is as follows:
[Liujx @ server235 static] $ gcc-wall file2.c file1.c-O file2
[Liujx @ server235 static] $./file2
Hello cobing!

In the above example, hello in file1.c is a static global variable, which can be called by printstr in the same file, but cannot be called by file2.c in different source files.

 

2. Static local variables

Common local variables are allocated in the stack space. When the function where the local variable is located is called for multiple times, the position of each call to this local variable on the stack is not necessarily the same. Local variables can also be dynamically allocated on the heap, but remember to release it after using the heap space.

Static local variable Chinese nameStatic local variables. Compared with common local variables, it has the following differences:

1)Location: Static local variables are stored in the global storage area by the compiler. data (Note: not in. BSS segment, see reason 3), so although it is local, it exists throughout the life cycle of the program.

2)Access permission: Static local variables can only be accessed by variables or functions in their scopes. That is to say, although it will exist throughout the life cycle 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 will be automatically assigned to 0 by the compiler, and the value after the last call will be used each time the static local variable is called. This is easy to understand. Every time a function calls a static local variable, it changes and leaves. The static local variable read from the global storage area next time is the last modified value.
The following are examples:

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

  1. # Include "file1.h"
  2. VoidPrintstr ()
  3. {
  4. IntNormal = 0;
  5. Static IntStat = 0;// This is a static local var
  6. Printf ("Normal = % D ---- stat = % d \ n", Normal, STAT );
  7. Normal ++;
  8. Stat ++;
  9. }

For ease of comparison, I have defined two variables: normal and static local variables stat, which are assigned with the initial value 0;

Call file1.h in file2.c:

    1. # Include "file1.h"
    2. IntMain ()
    3. {
    4. Printstr ();
    5. Printstr ();
    6. Printstr ();
    7. Printstr ();
    8. Printf ("Call stat in main: % d \ n", STAT );
    9.  Return0;
    10. }

This call will report an error because file2.c references the static local variable stat in file1.c, as shown below:

[Liujx @ server235 static] $ gcc-wall file2.c file1.c-O file2
File2.c: In function 'main ':
File2.c: 9: Error: 'STAT' is not declared (used for the first time in this function)
File2.c: 9: Error: (even if it appears multiple times in a function, each undeclared identifier
File2.c: 9: Error: only one report is reported in the function .)

The compiler says stat is not declared because it does not see stat in file1.c. Note this line below:

    1. # include "file1.h"
    2. int main ()
    3. {
    4. printstr ();
    5. printstr ();
    6. printstr ();
    7. printstr ();
    8. // printf ("Call stat in main: % d \ n", STAT );
    9. return 0;
    10. }

[Liujx @ server235 static] $ gcc-wall file2.c file1.c-O file2
[Liujx @ server235 static] $./file2
Normal = 0 ---- stat = 0
Normal = 0 ---- stat = 1
Normal = 0 ---- stat = 2
Normal = 0 ---- stat = 3
Run the command as shown above. It can be seen that every time a function is called, common local variables are re-allocated, while static local variables keep the value of the last call unchanged.

It should be noted that due to this feature of static local variables, functions with static local variables become non-reentrant, that is, each call may produce different results. This may become a hidden risk in multi-threaded programming. Pay more attention to it.

3. Static Functions
I believe you still remember the private functions in C ++ object-oriented programming. Private functions can be accessed only by the member variables or member functions of this class. In the C language, there are also "private functions", which are the static functions to be discussed next, to complete the private functions in object-oriented programming.

When your program has many source files, you will surely make a source file provide only some interfaces that are required by the outside world. Other functions may be written to implement these interfaces, you may not want these other functions to be seen by the outside world (not the source file). In this case, you can use static to modify these "other functions ".

So the scope of the static function is the source file. You can think of it as the private function in the object-oriented model.

The following are some examples:

File1.h is as follows:

    1. # Include <stdio. h>
    2. Static IntCalled ();
    3. VoidPrintstr ();

File1.c is as follows:

  1. # Include "file1.h"
  2. Static IntCalled ()
  3. {
  4. Return6;
  5. }
  6. VoidPrintstr ()
  7. {
  8. IntReturnval;
  9. Returnval = called ();
  10. Printf ("Returnval = % d \ n", Returnval );
  11. }

In file2.c, call the two functions declared in file1.h. Here we call called ():

    1. # Include "file1.h"
    2. IntMain ()
    3. {
    4. IntVal;
    5. Val = called ();
    6. Printstr ();
    7. Return0;
    8. }

An error is reported during compilation:

[Liujx @ server235 static] $ gcc-wall file2.c file1.c-O file2
File1.h: 3: Warning: 'called' used but never defined
/Tmp/ccylubzu. O: In function 'main ':
File2.c :(. Text + 0x12): Undefined reference to 'called'
Collect2: LD returns 1
Because the static function in file1.h is referenced, the system prompts in file2.c that this function cannot be found: Undefined reference to 'called'

Modify file2.c as follows:

    1. # Include "file1.h"
    2. IntMain ()
    3. {
    4. Printstr ();
    5. Return0;
    6. }

Compile and run:

[Liujx @ server235 static] $ gcc-wall file2.c file1.c-O file2
[Liujx @ server235 static] $./file2
Returnval = 6

Static functions can effectively solve the problem of the same name of functions in different original files, because a source file is invisible to the static functions in other source files.

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.