Extern variables in C language

Extern variables in C language

extern variable is the expansion of global variables.

Global (global) variables

Variables declared outside of any function is a global variables, global variables can be invoked by any declaration of a function where the file. Global variables can only be defined once.
int globalVar

When globalVar defined as global variables, default initial value is 0, and it has been assigned a respective system memory. Now, any file that defines a function of the variable can call it.

extern variables

If you want to call a global variable to another file, if you then declare global variables with the same name, the compiler error because of the same name, this time we should use extern variable.
extern int globalVar

extern declaration tells the compiler that this variable is defined in other files, it does not allocate memory for it.

example

#main.c

#include<stdlib.h>
#include<stdio.h>
#include"test.h"

int a; /* global variable */

int main(int argc, char** argv)
{
        a = 10;
        func();

        return 0;
}

#test.h

extern int a
int func();


# test.c

#include"test.h"
#include"stdio.h"

int func()
{
        printf("value of a is %d", a );
}
$ gcc main.c test.c -o main
$ ./main
value of a is 10

reference

How to use an extern variable in C?

Guess you like

Origin www.cnblogs.com/zchen1995/p/12173648.html