Jeff Abrahamson on Thu, 21 Nov 2002 22:10:05 -0500


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

[PLUG] C #define wizardry question


I'm trying to write a C macro like this:

    #define set(x) { x##_ = 1; printf("The variable "##x##"_ is set.\n"); }

So then I want to be able to say

    set(dog);
    set(cat);

and have it expand to

    { dog_ = 1; printf("The variable dog_ is set.\n"); };
    { cat_ = 1; printf("The variable cat_ is set.\n"); };

Unfortunately, the incantation in the printf doesn't work.

The real example, naturally, is complicated enough to warrant wanting
to get this right. Indeed, the real example generates quite a bit of
code, including several whole functions. All of which works except the
printf.

Note that the two obvious answers

    #define p(x) printf("x");
    #define q(x) printf("%s", x);
    p(dog);
    q(cat);

expand respectively to the following (incorrect) code:

    printf("x");	/* x, not dog */
    printf("%s", cat);	/* cat, not "cat" */

Any ideas?

-- 
 Jeff

 Jeff Abrahamson  <http://www.purple.com/jeff/>
 GPG fingerprint: 1A1A BA95 D082 A558 A276  63C6 16BF 8C4C 0D1D AE4B

Attachment: pgpHPID1hT0dS.pgp
Description: PGP signature