logo

Automatic Enum Stringification in C via Build-Time Code Generation

Posted by yairlenga |3 hours ago |1 comments

yairlenga 3 hours ago

If you maintain C code, you've probably written enum-to-string conversion functions by hand (either with switch statement, lookup tables or similar).

I wrote about autoamtic enum stringification in C - using build-time code generation from the DWARF debug information that is produced by the GCC/Clang compilers. (Medium, no Paywall).

I found the approach to reduce effort and errors for producing debug printout, logging, parsing config files, etc.

At the end, the developer can write something like:

  enum country_code {
    ISO3_AFG = 4,    /* Afghanistan */
    ISO3_ALB = 8,    /* Albania */
    ISO3_ATA = 10,   /* Antarctica */
    ISO3_DZA = 12,   /* Algeria \*/
    ...
  } ;

  ENUM_DESCRIBE(country3, country_code)

  void foo(enum country_code c)
  {
    printf("Called with C=%s\n", ENUM_LABEL_OF(country3, c))  ;
  }

Sharing in the hope that other developer can use this code. Can be integrated into any code with files (".c" source, ".h" header and python code generator) - available on my GitHub (MIT License).

Any feedback will be appreciated.