Mapping enum values to strings in C++

こ雲淡風輕ζ 提交于 2020-01-22 16:26:08

问题


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.


回答1:


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>



回答2:


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?




回答3:


This may be helpful to you:

The "stabs" debug format



来源:https://stackoverflow.com/questions/1884229/mapping-enum-values-to-strings-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!