本文介绍了令牌粘贴和 __LINE__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的宏来显示 TRACE 信息.

这是我正在使用的,

#ifdef __DEBUG__#define TRACE { PrintErrorMsg("跟踪异常在 " __FILE__ "LineNo:"##(__LINE__) "函数: " __FUNCTION__ " " );}#别的#define 跟踪#万一

这适用于 FILE,但它似乎不适用于 LINE ,知道我该如何处理.我也已经尝试过字符串运算符.这是如下.

#ifdef __DEBUG__#define TRACE { PrintErrorMsg("跟踪异常在 " __FILE__ "LineNo:"#(__LINE__) "Function: " __FUNCTION__ " " );}#别的#define 跟踪#万一

并且没有参数和双参数,例如 - __LINE__((__LINE__))知道我该如何处理这个问题吗?

我想出了这个,

#ifdef __DEBUG__#define ERROR_MSG_BUF_SIZE 1024#define TRACE { char * error_msg_buffer = new char[ERROR_MSG_BUF_SIZE];sprintf(error_msg_buffer,"跟踪文件异常:%s,行:%d,函数 %s
",__FILE__,__LINE__,__FUNCTION__);​​PrintErrorMsg(error_msg_buffer);删除[] error_msg_buffer;}#别的#define 跟踪

但我想在不使用 sprintf 的情况下做到这一点,只需通过字符串和令牌粘贴即可.有什么想法吗?

#endif

--提前致谢--

解决方案

不幸的是,你需要这种愚蠢.

#include <stdio.h>#define TRACE2(f,l) printf("我在文件中:" f " 和行:" #l "
")#define TRACE1(f,l) TRACE2(f,l)#define TRACE() TRACE1(__FILE__, __LINE__)诠释主要(无效){痕迹();痕迹();}

我在文件:test.cpp 和行:9
我在文件:test.cpp 和行:10

I'm writing a simple macro to show TRACE information.

This is what I'm using ,

#ifdef __DEBUG__
#define TRACE  { PrintErrorMsg("Trace exception at " __FILE__  "LineNo:"##(__LINE__) "Function: " __FUNCTION__ " " );}
#else
#define TRACE
#endif

This is working with FILE, but it doesn't seems to work with LINE ,Any idea how could I deal with this. I already tried stringing operator too.Which is asbellow.

#ifdef __DEBUG__
#define TRACE  { PrintErrorMsg("Trace exception at " __FILE__  "LineNo:"#(__LINE__) "Function: " __FUNCTION__ " " );}
#else
#define TRACE
#endif

and without parms and with double parms , ex - __LINE__ or ((__LINE__))Any idea how could I deal with this problem?

And I come up with this,

#ifdef __DEBUG__
#define ERROR_MSG_BUF_SIZE 1024
#define TRACE  { char * error_msg_buffer = new char[ERROR_MSG_BUF_SIZE];
                 sprintf(error_msg_buffer,"Trace Exception at file: %s ,Line : %d , Function %s
",__FILE__,__LINE__,__FUNCTION__);
PrintErrorMsg(error_msg_buffer );
delete[] error_msg_buffer;}
#else
#define TRACE

But I want to do it without using sprintf , just only by stringing and token pasting.Any idea?

#endif

--Thanks in advance--

解决方案

You need this kind of silliness, unfortunately.

#include <stdio.h>

#define TRACE2(f,l) printf("I am at file: " f " and line: " #l "
")
#define TRACE1(f,l) TRACE2(f,l)
#define TRACE() TRACE1(__FILE__, __LINE__)

int main(void)
{
    TRACE();
    TRACE();
}

这篇关于令牌粘贴和 __LINE__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:48
查看更多