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;