The usage of static and extern in C

Source: Internet
Author: User

I. static and extern:
In large projects, we will encounter many source files.

File a. c
Static int I; // only used in file
Int j; // used in the project
Static void init () // only used in file
{
}
Void callme () // used in the project
{
Static int sum;
}
The above global I variables and init () functions can only be used in the. c file, and the scope of the global variable sum is only in callme. The limitations of variable j and function callme () are extended to the entire project file. Therefore, you can use the extern keyword to call in B. c below. Extern tells the compiler that the variable or function has been defined in other files.

File 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 file, it is necessary to add extern to tell the compiler to name a function in the c mode:

File A. cpp calls the variables I and callme () in a. c ()
Extern "C" // call the variables in the c file
{
Int j;
Void callme ();
}
Int main ()
{
Callme ();
}

Ii. static rules:
A. if the global variable is only accessed in A single C file, you can change the variable to A static global variable to reduce the coupling between modules;
B. If the global variable is only accessed by a single function, you can change the variable 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.