1 Basic explanations
extern can be placed before a variable or function to mark the definition of a variable or function in another file, prompting the compiler to find its definition in other modules when it encounters this variable and function.
In addition, extern can also be used for link designation.
2 Question: extern variable
An array is defined in a source file:
Char a[6];
The following statement was declared in another file:
extern char *a;
Excuse me, is this OK?
Answer and Analysis:
1, can not, the program will tell you when the operation of illegal access. The reason is that pointers to type T are not equivalent to arrays of type T. The extern char *a declares a pointer variable instead of a character array, and therefore differs from the actual definition, resulting in illegal access at run time. The declaration should be changed to extern char a[].
2), example analysis as follows, if a[] = "ABCD", then the external variable a=0x61626364 (ABCD ASCII code value), *a obviously meaningless, the following figure:
Obviously a point of space (0x61626364) is meaningless and prone to illegal memory access.
3, this prompts us, in the use of extern time to strictly correspond to the declaration when the format, in actual programming, such errors are not uncommon.
4, extern used in variable declarations often have such a role, you declare a global variable in the *.C file, the global variable if you want to be referenced, put in the *.h and declared with extern.
3 question: extern function 1
Often see extern placed in front of a function as part of a function declaration, so what does the C language keyword extern do in the declaration of a function?
Answer and Analysis:
If the declaration of a function has the keyword extern, it simply implies that the function may be defined in another source file, with no other effect. That is, there are no obvious differences between the following two function declarations:
extern int f (); and int f ();
Of course, the use of this is in the program to replace the include "*.h" to declare functions, in some complex projects, I am more accustomed to all the function declarations before adding extern decoration.