Life Cycle of external variables: starts when the program is executed (not a function) and ends when the program ends.
Can external variables be referenced across files (that is, multiple files operate on the same variable )? Yes, but it must be declared
The main file defines an external variable.
A. c file is added to reference the external variables defined in the main file.
Error
[MACG @ localhost mysqltmp] $ make Gcc-C generatedatafile. c Generatedatafile. C: In function datafile Generatedatafile. C: 16: Error: mqlstream undeclared (first use in This function) |
Solution: Cross-file external variables must be declared
VI generatedatafile. c Extern MySQL Sqlstream; |
[MACG @ localhost mysqltmp] $ Make Gcc-C Liu. c Gcc-C generatedatafile. c Gcc-G main. O Liu. O generatedatafile. O-o Liu-L/usr/lib/MySQL -Lmysqlclient -LZ |
Two types of external variable Declaration
Used to reference "external variables defined under the function" in the function"
External variables used to reference other file definitions across files
In the same file, external variable references and definitions do have scope problems. They must be defined first and applied later,
Because the program is executed sequentially from top to bottom
The following is an error external variable definition:
$ VI test. c # Include <stdio. h> Main () { TTT = 7;
Menu (); ... Printf ("from main TTT is % d", TTT ); } Menu () { Printf ("TTT is % d/N", TTT ); ... }Int TTT; |
$ Gcc-O test. C-lcomm Test. C: In function main () Test. C: 6: Error: TTT undeclared (first use in this function) Test. C: 6: Error: (each undeclared identifier is reported only Once Test. C: 6: Error: for each function it appears in .) Test. C: In function menu () Test. C: 16: Error: TTT undeclared (first use in this Function) |
But can variables be defined later? Yes, but the variable Declaration must be added to the previous variable reference. (It is more cumbersome to define a function)
$ VI test. c # Include <stdio. h> Main () { Extern int TTT;
TTT = 7;Menu (); ... Printf ("from main TTT is % d", TTT ); } Menu () { Extern int TTT;
Printf ("TTT is % D/N ", TTT );
... } Int TTT;
|
$ Gcc-O test. C-lcomm $./Test TTT is 7 -------- 1 -------- 2 -------- 3 -------- 4 Input slot: -------> 3 From Main TTT is 7 |
Unlike external variables, the reference and definition of functions are normal in the same file. The function scope is the entire file.
# Include <stdio. h> Main () { Int rowcount, colcount, I, j, RET, test; Char A [5], B [5], s [80];Menu ();
Printf ("input slot: -------> "); Scanf ("% s", ); While (! Checknumber (A) scanf ("% s", ); } Menu ()
{ Printf ("-------- 1/N "); Printf ("-------- 2/N "); Printf ("-------- 3/N "); Printf ("-------- 4/N "); } |
$ Gcc-O test. C-lcomm $./Test -------- 1 -------- 2 -------- 3 -------- 4 Input slot: -------> 3 |