C ++ Program It is usually composed of many files. To allow multiple files to access the same variables, C ++ distinguishes between declarations and definitions.
The definition of a variable is used to allocate storage space for the variable. You can also specify the initial value for the variable. In a program, variables have only one definition.
The Declaration is used to indicate the type and name of the variable to the program. Definition is also Declaration: when defining a variable, we declare its type and name. You can declare a variable name without defining it by using the extern keyword.
Declarations that do not define variables include the object name, object type, and the keyword extern before the object type:
Extern int I; // declares but does not define I
Int I; // declares and defines I
The extern declaration is neither a definition nor a bucket. In fact, it only indicates that the variable is defined elsewhere in the program. Variables in the program can be declared multiple times, but can only be defined once.
Only when the Declaration is a definition can the Declaration have an initialization type, because only the definition can allocate storage space. The initialization type must have a bucket for initialization. If the Declaration has an initialization type, it can be considered as a definition, even if the declaration is marked as extern:
Extern double Pi = 3.1416; // Definition
Although extern is used, this statement defines Pi, allocates and initializes the bucket. The initialization type can be included only when the extern declaration is outside the function.
Because the initialized extern declaration is treated as a definition, any subsequent definition of this variable is incorrect:
Extern double Pi = 3.1416; // Definition
Double PI; // error: redefinition of Pi
Similarly, the subsequent extern declaration containing the initialization is also incorrect:
Extern double Pi = 3.1416; // Definition
Extern double PI; // OK: Declaration not Definition
Extern double Pi = 3.1416; // error: redefinition of Pi
The differences between declarations and definitions may seem insignificant, but they are actually important.
In C ++, variables must be defined only once and must be defined or declared before they are used.
Any variables used in multiple files must be declared separate from definitions. In this case, a file contains the definition of the variable, and other files that use the variable contain the declaration (rather than definition) of the variable ).
Summary:
1. variables must be defined or declared before use.
2. In a program, a variable can be defined only once, but can be declared multiple times.
3. Define the bucket to be allocated without declaring it.