prev up next   top/contents search

comp.lang.c FAQ 列表· 问题 10.27

Q如何包含 __FILE__ 和 __LINE__ 的展开__FILE____LINE__宏的展开?


A这个问题倾向于归结为问题 10.26。一种解决方案是编写宏,使用可变参数函数(参见问题 15.415.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 _ ,
技巧。

其他链接: 另一个想法


prev up next   contents search
关于此 FAQ 列表   关于 Eskimo   搜索   反馈   版权

Eskimo North 托管