Use of static and extern in C Language

Source: Internet
Author: User

Under the big project, we will encounter many source documents.

Document a. c

Static int I; // only used in document

Int j; // used in the project

Static void init () // only used in document

{

}

Void callme () // used in the project

{

Static int sum;

}

The above global I variables and init () functions can only be used in document a. c, and the scope of global variable sum is only in callme. The limitations of variable j and function callme () are extended to the entire project document. Therefore, the following B. c can be called with the extern keyword. Extern tells the compiler that this variable or function has been defined in other documents.

Document B .C

Extern int j; // call

Extern void callme (); // call

Int main ()

{

...

}

In addition, when C and C ++ are mixed programming, if c ++ calls a function or variable defined in the c source document, so we need to add extern to tell the compiler to name the function in c mode:

Document A. cpp calls the variables I and callme () in a. c ()

Extern "C" // call the variable in c document in c ++ document

{

Int j;

Void callme ();

}

Int main ()

{

Callme ();

}

Ii. static rules:

A. if the global variable is only accessed in A single C document, the variable can be changed to A static global variable. tbw can reduce the coupling between modules;

B. If the global variable is only accessed by a single function, the variable can be changed to the static local variable of the function to reduce the coupling between modules;

C. When designing and using functions that access dynamic global variables, static global variables, and static local variables, you need to consider re-import;

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.