Q如何包含 __FILE__ 和 __LINE__ 的展开__FILE__和__LINE__宏的展开?
A这个问题倾向于归结为问题 10.26。一种解决方案是编写宏,使用可变参数函数(参见问题 15.4 和 15.5),以及一个辅助函数,该函数将 __FILE__ 和 __LINE__ 的值__FILE__和__LINE__存储在静态变量中,如下所示:
#include <stdio.h> #include <stdarg.h> void debug(const char *, ...); void dbginfo(int, const char *); #define DEBUG dbginfo(__LINE__, __FILE__), debug static const char *dbgfile; static int dbgline; void dbginfo(int line, const char *file) { dbgfile = file; dbgline = line; } void debug(const char *fmt, ...) { va_list argp; fprintf(stderr, "DEBUG: \"%s\", line %d: ", dbgfile, dbgline); va_start(argp, fmt); vfprintf(stderr, fmt, argp); va_end(argp); fprintf(stderr, "\n"); }有了这些机制,调用
DEBUG("i is %d", i);就会展开成
dbginfo(__LINE__, __FILE__), debug("i is %d", i);并打印出类似以下的内容:
DEBUG: "x.c", line 10: i is 42
一个巧妙的改进是让存储函数返回一个指向实际可变参数函数的指针
void debug(const char *, ...); void (*dbginfo(int, const char *))(const char *, ...); #define DEBUG (*dbginfo(__LINE__, __FILE__)) void (*dbginfo(int line, const char *file))(const char *, ...) { dbgfile = file; dbgline = line; return debug; }有了这些定义,
DEBUG("i is %d", i);就会展开成
(*dbginfo(__LINE__, __FILE__))("i is %d", i);
另一种,可能更简单的方法可能是简单地
#define DEBUG printf("DEBUG: \"%s\", line %d: ", \ __FILE__,__LINE__),printf现在,
DEBUG("i is %d", i);就会简单地展开成
printf("DEBUG: \"%s\", line %d: ", __FILE__,__LINE__),printf("i is %d", i);
最后,你也许能够使用问题 10.26 中的
#define _ ,技巧。
其他链接: 另一个想法