An E(x)tern Newbie Question

I want to know how to declare a const variable in one file and access it from other files? (C++). It’s a fairly basic question, and reveals that you have to study more C++. What you want is to define a const variable at global scope. Unlike non-const variables (which are extern by default), const variables are local to the file in which they are defined. Therefore, you cannot access them from other files unless you specify that the variable is extern. For instance, if you specify extern when defining the variable

bufferSize in file1.ccextern const int bufferSize = 512;

you can access bufferSize from any other file, say, file2.cc

extern const int bufferSize; // we are using bufferSize from file1.cc

And that’s it.

This entry was posted in programming and tagged , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

One Comment