1

I am working with a generated header file which has the following map between state names and values:

#define START 0
#define IDLE 1
#define RESET 2
etc...

With the given API, I can get the value of the current state. This is fine in most cases, however I would like to get the name of the state to print to a debug console for easy debugging.

Is there any way I can abuse the preprocessor to get the name of the macro when I know its value?

At the moment I have a lookup table between the name and value, but this isn't a great solution since the macros in the header file change when it is regenerated.

I already tried some suggestions from here but didn't have much success.

  • 1
    Could you not generate a `debug_names` array at the same time you are generating the `#define`s? – eddiem Nov 18 '16 at 20:39
  • Is [this previous question](http://stackoverflow.com/questions/11693219/macro-expansion-and-stringification-how-to-get-the-macro-name-not-its-value-s) of use? Though as the above comment says, if it is generated code... – Weather Vane Nov 18 '16 at 20:45
  • Unfortunately the file is generated by an external program and I'm just supposed to use it 'as is'. I will take a look at that other question though, thanks. –  Nov 18 '16 at 20:50
  • you could include the source file as-is in your configuration files and parse the #defines to get the values and the strings associations. – Jean-François Fabre Nov 18 '16 at 20:53
  • Why not represent these values as an enumeration? This previous post shows how to print out the enum's names using macros. http://stackoverflow.com/questions/9907160/how-to-convert-enum-names-to-string-in-c – Stephen Nov 18 '16 at 20:55
  • @Stephen As I said, the header file is generated by an external program so I can't really modify it. –  Nov 18 '16 at 21:28
  • Also, I do not believe my question is a duplicate of the one linked @WeatherVane –  Nov 18 '16 at 21:38
  • Why is is not a duplicate? That your definitions are generated turns out to be irrelevant, it you cannot change that. The dup shows how to stringify macro names, which is what you asked. If you are trying to reverse a value to its macro definiton, perhaps this an X-Y question. – Weather Vane Nov 18 '16 at 21:59
  • ... but has an obvious answer. `if(var == IDLE) { /* stringify IDLE */ }` – Weather Vane Nov 18 '16 at 22:18

0 Answers0