Archives for: May 2005, 22

05/22/05

C preprocessor magic

Did you ever run in this situation where you need to #define some string, and use it both as a function name and as a string? As you might have discovered it is not easily possible to do this.

I ran into this problem today, and found out you got to solve it using 2 extra macro's (thanks to this page):

#include <stdio.h>

#define xstr(s) str(s)
#define str(s) #s

#define FOO foobar

void FOO() {
        printf("In %s\n" xstr(FOO));
}

int main() {
        /* This won't work because FOO is no string */
        /* printf("FOO is \"%s\"\n", FOO); */
        printf("FOO is \"%s\"\n", xstr(FOO));
        FOO();
        return 0;
}

which gives the desired result:

FOO is "foobar"
In foobar

and inspecting the output of nm, the function is correctly called "foobar", not "FOO". Jay!

[edit] Once more I just got blown away by what glib offers you. G_STRINGIFY is defined by default when you include glib.h (in glib/gmacros.h more precisely).

Permalink . Ikke . 06:08:15 pm . 176 Words . Coding Corner . . 949 views . Leave a comment

Kleren politie-stripact in beslag genomen

HERENT- Bij de controle van een voertuig trof de politie van Herent zaterdag twee inzittenden aan die volledig gekleed waren in een politie-uniform. De nep-agenten wilden in een caf

Permalink . Peter . 14:45:32 . 106 Words . Life & Fun . Email . No views