For automatic and register variables, there is no difference between a definition and a declaration. The process of declaring an automatic or register variable determines the name of the variable and allocates the appropriate memory.
However, for external variables: Since the memory for the variable should be assigned only once to ensure that access to the variable always refers to the same cell. all variables must be defined once and only once.
If an external variable is to be used in a file different from the one in which it is defined, a mechanism is needed to โconnectโ such use with a uniquely defined external variable allocated for it. This process of linking the same external variable in different files is called link resolution.
It can be defined and declared using the declaration operator outside of any function without a storage class specifier. This declaration allocates memory for the variable. The declaration operator can also be used to simply declare a variable name using the extern storage class specifier at the beginning of the declaration. This declaration indicates that the variable is defined elsewhere, i.e. the memory for this variable is allocated in another file. Thus, access to an external variable in a file other than the one in which it is defined is possible if it is declared with the extern keyword; no new memory is allocated. This declaration tells the compiler that the variable is defined elsewhere, and the code is compiled with an external variable left unresolved. The reference to an external variable is allowed during the build process.
Ex. Code: //file1.c extern char stack[10]; extern int stkptr; .... //file2.c char stack[10]; int stkptr; ....
These declarations tell the compiler that the variables stack [] and stkptr are defined elsewhere, usually in some other file. If the extern keyword was omitted, the variables will be considered new and memory will be allocated for them. Remember that access to the same external variable defined in another file is only possible if the declaration uses the extern keyword.
user401519
source share