views:

255

answers:

3

Is there a way to, at runtime, map the value of an enum to the name? (I'm building with GCC.)

I know GDB can do it and I'm willing to use something that's unportable and mucks with debug data.


Edit: I'm looking for a solution that doesn't require modifying the original enum declaration nor hand copying all the values out in a mapping function. I already know how to do both of those.

Effectively; I want a function that does whatever GDB does when it formats runtime enum values.

A: 

This may be helpful to you:

The "stabs" debug format

Goz
That would be useful for the guy who writes the library I'm looking for.
BCS
When you provide a link, please give a one-sentence summary (at least) of what it links to.
anon
+3  A: 

If you have tenacity, you could create a tool that will parse source files for enums, generate the translation functions and add them to the source code. With more energy, you could write plugins for editors such as Eclipse and Emacs that will perform this for you.

Perhaps it could be done in a Perl script?

Thomas Matthews
In a previous job we had a fairly thorough system to define all return codes in enums and a Perl script to pull them out and make a compileable file of strings so they could be printed when error occurred. These days I would probably use Python but Perl got the job done.
Steve Fallows
+1  A: 

If you don't want to invest the time to utilize GCCs symbol information, gcc-xml provides you information about C++ sources in a reusable XML format, including enumeration names.

Simplified example... this source:

enum E {
  e1 = 1,
  e2 = 42
};

becomes:

<GCC_XML>
  <!-- ... -->
  <Enumeration name="E">
    <EnumValue name="e1" init="1"/>
    <EnumValue name="e2" init="42"/>
  </Enumeration>
  <!-- ... -->
</GCC_XML>
Georg Fritzsche