Search code examples
cmacrostokenc-preprocessorstringification

C Programming: Preprocessor, macros as tokens


I'm trying to do something that is conceptually similar to this, but can't seem to get it to work (error shown at end) any ideas?

#include <stdio.h>

int main( int argc , char const *argv[] )
{
  int abc_def_ghi = 42;
  #define SUFFIX ghi
  #define VAR(prefix) prefix##_def_##SUFFIX
  printf( "%d\n" , VAR(abc) );
  return 0;
}

// untitled:8: error: ‘abc_def_SUFFIX’ undeclared (first use in this function)

Solution

  • You just need additional indirection:

    #include <stdio.h>
    
    int main( int argc , char const *argv[] )
    {
      int abc_def_ghi = 42;
      #define SUFFIX ghi
      #define VAR3(prefix, suffix) prefix##_def_##suffix
      #define VAR2(prefix, suffix) VAR3(prefix, suffix)
      #define VAR(prefix) VAR2(prefix, SUFFIX)
      printf( "%d\n" , VAR(abc) );
      return 0;
    }
    

    Even though it looks redundant, it's not.