Edu Felipe Edu Felipe - 1 year ago 92
C++ Question

Is there a simple way to convert C++ enum to string?

Suppose we have some named enums:

enum MyEnum {
BAR = 0x50

What I googled for is a script (any language) that scans all the headers in my project and generates a header with one function per enum.

char* enum_to_string(MyEnum t);

And a implementation with something like this:

char* enum_to_string(MyEnum t){
case FOO:
return "FOO";
case BAR:
return "BAR";
return "INVALID ENUM";

The gotcha is really with typedefed enums, and unnamed C style enums. Does anybody know something for this?

EDIT: The solution should not modify my source, except for the generated functions. The enums are in an API, so using the solutions proposed until now is just not an option.

Answer Source

You may want to check out GCCXML.

Running GCCXML on your sample code produces:

  <Namespace id="_1" name="::" members="_3 " mangled="_Z2::"/>
  <Namespace id="_2" name="std" context="_1" members="" mangled="_Z3std"/>
  <Enumeration id="_3" name="MyEnum" context="_1" location="f0:1" file="f0" line="1">
    <EnumValue name="FOO" init="0"/>
    <EnumValue name="BAR" init="80"/>
  <File id="f0" name="my_enum.h"/>

You could use any language you prefer to pull out the Enumeration and EnumValue tags and generate your desired code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download