1. by Default,
const
Objects is Local to a File
By default, the const object is local
This is the original in "C + + primary 5th."
When a const object was initialized from a Compile-time constant, such as
Definition of BufSize:
- Const int bufSize = +; //input buffer size
The compiler would usually replace uses of the variable with its corresponding value during compilation. That is, the compiler would generate code using the value of the places, that's our code uses bufSize.
To substitute the value for the variable, the compiler have to see the variable ' s initializer. When we split a program into multiple files, every file that uses the const must has access to its initializer. In order to see the initializer, the variable must is defined in every file, and wants to use the variable ' s value (§2.2. 2, p. 45). To support this usage, yet avoid multiple definitions of the same variable, const variables is defined as local to the fi Le. When we define a const with the same name in multiple files, it's as if we had written definitions for separate variables In each file.
This means that when we define a const object (which must be initialized), the compiler needs to use its corresponding initialization value instead of the object we define. In order to get the initialization value, the compiler needs to access initializer. According to (§2.2.2, p. 45), the object can have only one definition. In the compile phase, the compiler is like the caller, and our const object is a callee for the compiler. When we split a program into multiple files, if there are multiple definitions for the same const object, the compiler will not be able to make a selection and will not be able to do the compilation work. Therefore, in order to satisfy each const object being initialized and avoid multiple definitions, the const variables is defined as local to the file. When we define a const object of the same name in more than one file, it is as if we were defining an unrelated object.
Example:
#const_test. h
void Printmsg ();
#const_test. cpp
#include <iostream>extern int varx_global;extern const int varz_global;void printmsg () { std::cout << "' Varx_global ' is ' << varx_global << '. ' << Std::endl; Std::cout << ' Varz_global ' is << varz_global << '. ' << Std::endl;
#main. cpp
#include <iostream> #include "const_test.h" int varx_global = 2001;extern const int Varz_global = 1998;//without Exte RN, the caller would be an error with Undifinedint main () { printmsg (); /* Output: ' Varx_global ' is 2001. ' Vary_global ' is 1998. */ return 0;}
Not to be continued
C + + const