Why not just make a function that prints a string representation of the enum value? That way you needn't muck around with extern at all, plus you can also catch use of any unrecognized enum values.
The header file:
Code:
#ifndef SYMBOLS_H
#define SYMBOLS_H
// include header file that provides forward declarations of input / output streams
#include <iosfwd>
enum symbol_t
{
error_k,
plus_k,
minus_k,
mult_k,
div_k,
lparen_k,
rparen_k,
numeric_k,
end_k
};
void print_symbol_t( symbol_t enumVal, std::ostream& out );
#endif
The source file:
Code:
#include "Symbols.h"
#include <sstream>
#include <stdexcept>
void print_symbol_t( symbol_t enumVal, std::ostream& out )
{
switch ( enumVal )
{
case error_k:
out << "error_k";
break;
case plus_k:
out << "plus_k";
break;
case minus_k:
out << "minus_k";
break;
case mult_k:
out << "mult_k";
break;
case div_k:
out << "div_k";
break;
case lparen_k:
out << "lparen_k";
break;
case rparen_k:
out << "rparen_k";
break;
case numeric_k:
out << "numeric_k";
break;
case end_k:
out << "end_k";
break;
default:
// Unrecognized enum value.
{
std::ostringstream errorMessage;
errorMessage << "Unrecognized symbol_t enum with integer value " << enumVal << "!";
throw std::runtime_error( errorMessage.str() );
}
}
}
EDIT: You can easily add a convenience function that returns a string, too.
Code:
#include <string>
#include <sstream>
std::string getStringRepresentation( symbol_t enumVal )
{
std::ostringstream out;
print_symbol_t( enumVal, out );
return out.str();
}