const
Objects Are Local to a FileWhen a const
object is initialized from a compile-time constant, such as in our definition of bufSize
:
const int bufSize = 512; // input buffer size
the compiler will usually replace uses of the variable with its corresponding value during compilation. That is, the compiler will generate code using the value 512
in the places that our code uses bufSize
.
To substitute the value for the variable, the compiler has to see the variable’s initializer. When we split a program into multiple files, every file that uses the const
must have access to its initializer. In order to see the initializer, the variable must be defined in every file that 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 are defined as local to the file. When we define a const
with the same name in multiple files, it is as if we had written definitions for separate variables in each file.
Sometimes we have a const
variable that we want to share across multiple files but whose initializer is not a constant expression. In this case, we don’t want the compiler to generate a separate variable in each file. Instead, we want the const
object to behave like other (nonconst
) variables. We want to define the const
in one file, and declare it in the other files that use that object.
To define a single instance of a const
variable, we use the keyword extern
on both its definition and declaration(s):
// file_1.cc defines and initializes a const that is accessible to other files
extern const int bufSize = fcn();
// file_1.h
extern const int bufSize; // same bufSize as defined in file_1.cc
In this program, file_1.cc
defines and initializes bufSize
. Because this declaration includes an initializer, it is (as usual) a definition. However, because bufSize
is const
, we must specify extern
in order for bufSize
to be used in other files.
The declaration in file_1.h
is also extern
. In this case, the extern
signifies that bufSize
is not local to this file and that its definition will occur elsewhere.