I don't quite understand the concepts behind using the extern
and const
keywords in C++.
I've read a few related questions on the subject ( see below ), but so far I haven't been able to get a grasp on how to use them together.
Related Questions:
- How do I share a variable between source files in C? With
extern
, but how? - What is the Difference Between a Definition and a Declaration?
- What is a Translation ( Compilation ) Unit?
- What Exactly is the One Definition Rule in C++?
Ok, take for example the following program code:
dConst.hpp
extern const int NUM_GENERATORS; // Number of generators in power plant
extern const int generatorID[NUM_GENERATORS]; // Generator ID numbers
extern const bool generatorStatus[NUM_GENERATORS]; // Generator Status
vConst.cpp
const int NUM_GENERATORS = 4; // Generators in Power Plant
const int generatorID[NUM_GENERATORS] = // Generator ID numbers
{
23, 57, 49, 106
};
const bool generatorStatus[NUM_GENERATORS] = // Production status ( online? )
{
true, false, false, true
};
main.cpp
#include <iostream>
#include "dConst.hpp"
using std::cout;
using std::cin;
using std::endl;
// ----====< M A I N >====----
int main()
{
for ( int iGenerator = 0; iGenerator < NUM_GENERATORS; iGenerator++ )
{
cout << "Generator ";
cout << generatorID[iGenerator];
if ( generatorStatus[iGenerator] )
cout << "is running." << endl;
else
cout << "is offline!" << endl;
}
cout << "Press ENTER to EXIT:";
cin.get(); // Stop
return 0;
}
I am unable to use NUM_GENERATORS
to declare my arrays full of generator ID's and statuses. I've included the external definitions at the top: #include "dConst.hpp
. From what I've read ( perhaps not closely enough ) on some of the StackOverflow questions here, the compiler and linker should be able to find the values defined in vConst.cpp, and continue on their merry way.
So why aren't they doing this?