如何在字符串中使用编译时常数__LINE__? [英] How can I use the compile time constant __LINE__ in a string?

查看:285
本文介绍了如何在字符串中使用编译时常数__LINE__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 __ LINE __ 作为方法参数,但我想要一个简单的方法在使用字符串的函数中使用它。

I can use __LINE__ as a method parameter just fine, but I would like an easy way to use it in a function that uses strings.

例如,我有这样的:

11    string myTest()
12    {
13     if(!testCondition)
14       return logError("testcondition failed");
15    }

我希望函数的结果是:


myTest第14行:testcondition失败

"myTest line 14: testcondition failed"

我可以写logError吗?

How can I write logError? Does it have to be some monstrosity of a macro?

推荐答案

为什么你还需要一个字符串?整数有什么问题?这里有两种方法可以写 logError()

Why do you even need it as a string? What's wrong with an integer? Here are two ways you could write logError():

#define logError(str) fprintf(stderr, "%s line %d: %s\n", __FILE__, __LINE__, str)

// Or, forward to a more powerful function
#define logError(str) logError2(__FILE__, __LINE__, str)
void logError2(const char *file, int line, const char *str);

如果你真的需要一个字符串,你可以使用字符串化操作符,但是由于宏的工作方式,您需要将它包装在两个宏中:

If you really need the line as a string, you can use the stringizing operator #, but because of the way macros work, you'll need to wrap it in two macros:

#define STRINGIZE(x) STRINGIZE2(x)
#define STRINGIZE2(x) #x
#define LINE_STRING STRINGIZE(__LINE__)

现在 LINE_STRING 是一个宏,将扩展为包含当前行号的字符串,如果你只有一个级别的宏(即如果你有 #define STRINGIZE(x)#x ),那么你会得到字符串 __LINE __每次展开它,这不是你想要的。

And now LINE_STRING is a macro that will expand to a string containing the current line number wherever it is expanded. If you only had one level of macros (i.e. if you had #define STRINGIZE(x) #x), then you would get the literal string "__LINE__" every time you expanded it, which is not what you want.

这篇关于如何在字符串中使用编译时常数__LINE__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆