Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In that case it's just to convert the value of a macro into a string constant

   cat > a.c
   #define X(s) #s
   #define S(s) X(s)
   char *f(void) return { S(A); }
   ^D

   cc -E a.c
   char *f(void) return { "A"; }
   
   cc -DA=B -E a.c
   char *f(void) return { "B"; }

More interestingly, you can use this trick to create code where some user-specified word appears as a string and as the name of the function. Exercice: write a macro M(x) such that compiling the code

    M(foo)
    M(bar)
results in

    void print_foo(void) { puts("foo"); }
    voir print_bar(void) { puts("bar"); }


> you can use this trick to create code where some user-specified word appears as a string and as the name of the function

Ah, the poor man's introspection and reflection with C macros.

shudder


Print an expression code to stdout using rich man’s introspection and reflection.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: