logoalt Hacker News

enriquto10/11/20241 replyview on HN

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"); }

Replies

delta_p_delta_x10/11/2024

> 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

show 1 reply