使用__FILE__得到当前源文件的文件名&使用__LINE__得到当前所在行数

来源:互联网 发布:广场舞 知乎 编辑:程序博客网 时间:2024/06/02 07:28

想用C++自己实现一个轻量级的日志文件类,记录运行时的错误信息、时间信息、错误发生的源代码文件名、错误发生所在行数。

实现后两个功能时遇到了些困难,后来在msdn上查到标准C++提供了一组宏,可以完美的解决这些问题。下面摘自MSDN:

 

-----------------------------------------------------------------------------------------------------------------------------------------------------

 

__FILE__   The name of the current source file. __FILE__ expands to a string surrounded by double quotation marks. To ensure that the full path to the file is displayed, use /FC (Full Path of Source Code File in Diagnostics).

You can create your own wide string version of __FILE__ as follows:

 

#include <stdio.h>

#define WIDEN2(x) L ## x

#define WIDEN(x) WIDEN2(x)

#define __WFILE__ WIDEN(__FILE__)

wchar_t *pwsz = __WFILE__;

 

-----------------------------------------------------------------------------------------------------------------------------------------------------

 

__LINE__   The line number in the current source file. The line number is a decimal integer constant. It can be altered with a#line directive.

 

-----------------------------------------------------------------------------------------------------------------------------------------------------

 

 

__FILE__得到的是单字符的字符串,当在Unicode中使用时,如果直接用__FILE__,会出现乱码,因此需要用上面的宏处理下得到__WFILE__,这个宏将返回双字节

 

__LINE__返回一个数   

 

 

e.g.  

在Unicode中

 

首先

#define WIDEN2(x) L ## x

#define WIDEN(x) WIDEN2(x)

#define __WFILE__ WIDEN(__FILE__)

 

然后

CString str;

#ifdef _UNICODE

str.Format(_T("%s line %d"), __WFILE__, __LINE__ );

#else

str.Format(_T("%s line %d"), __FILE__, __LINE__ );

#endif

MessageBox(str);