Saturday, May 09, 2009
Magic of C preprocessor
Curtis Krauskopf discusses a neat trick which forces C preprocessor to merge __FILE__ and __LINE__ as one string, which isn't straightforward since __FILE__ is a string but __LINE__ is an integer.
It turns out you can solve the problem with two additional macros:
#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
printf("Error at %s: %s\n", location, msg);
}
int main(int , char**)
{
error(AT, "fake error");
return 0;
}
Now, if only someone could find a way to merge __func__ and __LINE__ ....
Labels: C
