Suppose we have some named enums:
enum MyEnum {
FOO,
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){
switch(t){
case FOO:
return "FOO";
case BAR:
return "BAR";
default:
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.
Here is a CLI program I wrote to easily convert enums to strings. Its easy to use, and takes about 5 seconds to get it done (including the time to cd to the directory containing the program, then run it, passing to it the file containing the enum).
Download here: http://www.mediafire.com/?nttignoozzz
Discussion topic on it here: http://cboard.cprogramming.com/projects-job-recruitment/127488-free-program-im-sharing-convertenumtostrings.html
Run the program with the "--help" argument to get a description how to use it.
This can be done in C++11
I want to post this in case someone finds it useful.
In my case, I simply need to generate
ToString()
andFromString()
functions for a single C++11 enum from a single.hpp
file.I wrote a python script that parses the header file containing the enum items and generates the functions in a new
.cpp
file.You can add this script in CMakeLists.txt with execute_process, or as a pre-build event in Visual Studio. The
.cpp
file will be automatically generated, without the need to manually update it each time a new enum item is added.generate_enum_strings.py
Example:
ErrorCode.hpp
Run
python generate_enum_strings.py ErrorCode.hpp
Result:
ErrorCode.cpp
You may want to check out GCCXML.
Running GCCXML on your sample code produces:
You could use any language you prefer to pull out the Enumeration and EnumValue tags and generate your desired code.
Further discussion on this method
Preprocessor directive tricks for newcomers
Here is an attempt to get << and >> stream operators on enum automatically with an one line macro command only...
Definitions:
Usage:
Not sure about the limitations of this scheme though... comments are welcome!