MACRO用格式化连接__FILE__和__LINE__

时间:2014-07-22 08:53:05

标签: c++ visual-c++ macros

我在我的名为Test.cpp的.cpp文件中以下列方式使用了宏,该文件位于c:\ Test \ Test.cpp

位置

内部test.cpp

#define FILE_NAME strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__
#define S1(x) #x
#define S2(x) S1(x)    
#define LOCATION FILE_NAME " : " S2(__LINE__)
//#define LOCATION __FILE__" : " S2(__LINE__) Working but giving the whole file path where as i need only Filename:Line number

Inside Function 
{
  ::MessageBox(NULL,LOCATION,"Test",MB_OK); //Here i am getting only Filename .
}

请帮我编写一个MACRO,这样我就可以在我的应用程序中获得文件名(不是完整路径,只有文件名)和行号。

1 个答案:

答案 0 :(得分:2)

您尝试将字符串文字与strrchr的结果连接起来。这是不可行的。你需要一个辅助函数,比如

std::string get_location(const std::string& file, int line)
{
  std::ostringstream ostr;
  size_t bspos = file.find_last_of('\\');
  if (bspos != std::string::npos)
    ostr << file.substr(bspos + 1) << " : " << line;
  else
    ostr << file << " : " << line;
  return ostr.str();
}

#define LOCATION (get_location(__FILE__, __LINE__))
相关问题