In "C++ Primer, Fifth Edition" on page 95. Talking about constants. He said:
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 theconst
object to behave like other (nonconst
) variables. We want to define theconst
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 keywordextern
on both its definition and declaration(s):
// file_1.cc
defines and initializes aconst
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
What I am not sure of is the last paragraph; I removed extern
from the definition of bufsize
but it is ok and is accessible from other files?!
const int bufSize = fcn(); // without keyword extern
Why he said we should add keyword extern
to both declarations and definition of bufsize
to be accessible from other files but extern
as I guess is enough in declarations?
Thank you for your help.