Ikke's Blog

Post details: C preprocessor magic

May 22
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));
        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).


No Comments for this post yet...

Leave a comment:

Your email address will not be displayed on this site.
Your URL will be displayed.

Allowed XHTML tags: <p, ul, ol, li, dl, dt, dd, address, blockquote, ins, del, span, bdo, br, em, strong, dfn, code, samp, kdb, var, cite, abbr, acronym, q, sub, sup, tt, i, b, big, small>
(Line breaks become <br />)
(Set cookies for name, email and url)
(Allow users to contact you through a message form (your email will NOT be displayed.))


Who's Online?

  • Guest Users: 456


XML Feeds

What is RSS?