Skip to content

Instantly share code, notes, and snippets.

@zenubis
Last active August 29, 2015 14:13
Show Gist options
  • Save zenubis/ec1f9e263bc80c622141 to your computer and use it in GitHub Desktop.
Save zenubis/ec1f9e263bc80c622141 to your computer and use it in GitHub Desktop.
// Taken from http://www.codeproject.com/Articles/10500/Converting-C-enums-to-strings
// File name: "EnumToString.h"
#undef DECL_ENUM_ELEMENT
#undef BEGIN_ENUM
#undef END_ENUM
#ifndef GENERATE_ENUM_STRINGS
#define DECL_ENUM_ELEMENT( element ) element
#define BEGIN_ENUM( ENUM_NAME ) typedef enum tag##ENUM_NAME
#define END_ENUM( ENUM_NAME ) ENUM_NAME; \
char* GetString##ENUM_NAME(enum tag##ENUM_NAME index);
#else
#define DECL_ENUM_ELEMENT( element ) #element
#define BEGIN_ENUM( ENUM_NAME ) char* gs_##ENUM_NAME [] =
#define END_ENUM( ENUM_NAME ) ; char* GetString##ENUM_NAME(enum \
tag##ENUM_NAME index){ return gs_##ENUM_NAME [index]; }
#endif
//------------- example header
// File name: "Days.h"
#if ( !defined(DAYS_H) || defined(GENERATE_ENUM_STRINGS) )
#if (!defined(GENERATE_ENUM_STRINGS))
#define DAYS_H
#endif
#include "EnumToString.h"
///////////////////////////////
// The enum declaration
///////////////////////////////
BEGIN_ENUM(Days)
{
DECL_ENUM_ELEMENT(sunday),
DECL_ENUM_ELEMENT(monday),
DECL_ENUM_ELEMENT(tuesday),
DECL_ENUM_ELEMENT(wednesday),
DECL_ENUM_ELEMENT(thursday),
DECL_ENUM_ELEMENT(friday),
DECL_ENUM_ELEMENT(saturday)
}
END_ENUM(Days)
//--------- example cpp
// File name: "EnumToString.cpp"
#ifdef _SECOND_TIME_IN_ENUM2STR_CPP
#define GENERATE_ENUM_STRINGS // Start string generation
#endif
#include "Days.h"
//#include "OtherEnum.h"
//#include "AnotherOne.h"
#ifdef _SECOND_TIME_IN_ENUM2STR_CPP
#undef GENERATE_ENUM_STRINGS // Stop string generation
#undef _SECOND_TIME_IN_ENUM2STR_CPP
#else
#define _SECOND_TIME_IN_ENUM2STR_CPP
#include "EnumToString.cpp"
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment