How to make preprocessor generate a string for __LINE__ keyword?

て烟熏妆下的殇ゞ 提交于 2019-12-02 21:10:09

You need the double expansion trick:

#define S(x) #x
#define S_(x) S(x)
#define S__LINE__ S_(__LINE__)

/* use S__LINE__ instead of __LINE__ */

Addendum, years later: It is a good idea to go a little out of one's way to avoid operations that may allocate memory in exception-handling paths. Given the above, you should be able to write

throw std::runtime_error("exception at " __FILE__ " " S__LINE__);

which will do the string concatenation at compile time instead of runtime. It will still construct a std::string (implicitly) at runtime, but that's unavoidable.

EDIT: In response to request on the other answer, I added a non-macro version:

#include <iostream>
#include <boost/lexical_cast.hpp>
#include <string>

#define B(x) #x
#define A(x) B(x)

void f(const char *s) {
std::cout << s << "\n";
}

int main() {

   f(A(__LINE__));
   f(boost::lexical_cast<std::string>(__LINE__).c_str());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!