2

I have used macros in following way in my .cpp file named Test.cpp which is present in the location c:\Test\Test.cpp

Inside 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 .
}

Please help me in writing a MACRO so that i can get both Filename(Not the full path , only Filename) and Line number in my application .

1
  • No , it prints from messagebox line only . Commented Jul 22, 2014 at 9:12

1 Answer 1

2

You try to concatenate string literal with the result of strrchr. This is not feasible. You will need a helper function, something like

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__))
Sign up to request clarification or add additional context in comments.

5 Comments

Is there any way to achieve the same through macro only ?
It should be doable with definiing macro returning std::string and then concatenating using + with colon and the line number. But I do not see any advantage over using a function.
I tried but unable to do it . Can you please help me in this ?
Here you go, but this code searches twice for backslash: #define FILE_NAME (strrchr(FILE, '\\') ? std::string(strrchr(FILE, '\\')+1) : std::string(FILE)) #define LOCATION (FILE_NAME + " : " + std::to_string(LINE))
std::to_string was added in C++11, maybe you use a compiler without C++11 support. Write then your own to_string in similar way as in the code in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.