Detailed resolution of the use of static and extern in c

  • 2020-04-02 01:44:52
  • OfStack

Static and extern:
We'll come across a lot of source documents in big projects.

Document a.c


static int i; //Only in document a
int j;    //Used in engineering
static void init()         //Only in document a
{
}
void callme()          //In engineering
{
   static int sum;
}

The above global I variable and init() function can only be used in the a.c document, and the global sum scope is only in the callme. The full limitation of the variable j and the function callme() extends to the entire project document. So you can call it with the extern keyword in the following b.c. Extern tells the compiler that the variable or function has been defined in another document.

Document biggest


extern int j;     //Call in document a
extern void callme();  //Call in document a
int main()
{
  ...
}

Another use of extern is when C and C++ are mixed programming. If C++ calls functions or variables defined by C source documents, add extern to tell the compiler to name functions in C:
Document a.cpp calls variable I and function callme() in A.c

extern "C"  //Call variables in c document in c++ document
{
   int j;
   void callme();
}
int main()
{
   callme();
}

2. Static law:
A. If the global variable is only accessed in A single C document, it can be modified to A static global variable to 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, the reentrant problem should be considered;


Related articles: