DEV Community

Cover image for Automatic Enum Stringification in C via Build-Time Code Generation
Yair Lenga
Yair Lenga

Posted on • Originally published at Medium

Automatic Enum Stringification in C via Build-Time Code Generation

The C compilers (gcc, clang, ...) capture lot of information about the code and store in the information as debug information. Sometimes, we can leverage this information and enhance our code with minimal effort.

I wrote about automatic enum stringifcation in C, using build-time code generation from DWARF debug info.

No manual lookup tables to build or maintain, no complex macros - just compile, extract and link.

The final binary contains plain C data structures with zero runtime dependency on DWARF libraries, or tools.

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)) ;
}
Enter fullscreen mode Exit fullscreen mode

Medium Article (No Paywall): Automatic Enum Stringification in C via Build-Time Code Generation


The process work in 4 steps:

  1. The C code that uses the enum is complied with debug mode (-g)
  2. A python program extract the enum definition from the object files, and generate the meta data that is needed to support the reflection as C code.
  3. The generated C code is compiled and linked into the final binary.
  4. At run time, the program read the meta data and and can complete the conversion with no additional dependencies.

Generating and using enum meta data

Curious about what other techniques are used to solve similar problem.

Top comments (0)