Usage of extern keyword

extern keyword

Externally available (global variables) extern----global static storage area

Standard definition format: extern type name variable name;

If a variable defined outside all functions does not specify its storage class, then it is an external variable and its scope is from the point of its definition to the end of this file (this is true in a single source file, if there are multiple source file, the scope of global variables is not from the variable definition to the end of the file, but is also valid in other files ), but if you want to use it before the definition point or in other files, you need to use the keyword extern Declare it (note that it is not defined, the compiler does not allocate memory for it)

Suggested optimal usage:
For example, define int a = 5 and a function in the ac file and write it in ah. extern int a;
If you want to call the variable and function a in other files, just #include "a.h"do it directly. As shown below

a.c

#include <stdio.h>

int data = 5;
int func(int a,int b)
{
    
    
        return a+b;
}

a.h

extern int data;
extern int func();

b.c

#include <stdio.h>
#include "a.h"
int main()
{
    
    
        printf("b.c data = %d\n",data);
        printf("func = %d\n",func(2,3));
        return 0;
}

Insert image description here

Question:
If a global variable is defined in the ac file and you want to use it in the main function, what should you do?

①Add an extern statement to the source file test.c containing the main function

a.c

#include <stdio.h>

int sum = 100;

int Max(int num1,int num2)
{
    
    
	int max = num1;
	
	if(num1 < num2){
    
    
		max = num2;
	}
	return max;
}

a.h

extern int Max(int num1, int num2);

test.c

#include <stdio.h>
#include "a.h"

int main()
{
    
    
	int a;
	
	a = Max(10,20);
	printf("%d   %d",a,sum);
	
	return 0;
}

②Declare the global variables in ac in the header file ah, and then include the header file ah in test.c

a.h

extern int Max(int num1, int num2);
extern int sum;

Guess you like

Origin blog.csdn.net/lijunlin0329/article/details/129008299