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));
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).
Comments:
No Comments for this post yet...