Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cpp preprocessor and basename of filename, line number as string

I'd like to produce a static string of the form "example.cpp:34" with the preprocessor, but the __FILE__ macro will expand to "lib/example/example.cpp" and __LINE__ expands to 34 as an integer. Can I construct the desired string with the preprocessor? GCC extentions are ok.

Edit The most important part here is that I want a static C-style string, so I can't use the basename function. I'm wondering if there's some way in the preprocessor to replicate that functionality, possibly with a boost extension?

like image 718
pythonic metaphor Avatar asked Nov 03 '22 10:11

pythonic metaphor


1 Answers

You can take advantage of the fact that adjacent string literals are concatenated:

#define STRINGIFY(s) #s
#define FILELINE(line) __FILE__ ":" str(line)

Then use it like FILELINE(__LINE__). I don't do this very often so there may be a better way than having to pass the __LINE__ macro. It works for me anyway, testing with:

#include <iostream>

#define str(s) #s
#define FILELINE(line) __FILE__ ":" str(line)

int main(int argc, const char* argv[])
{
  std::cout << FILELINE(__LINE__) << std::endl;
  return 0;
}

I get:

main.cpp:9
like image 118
Joseph Mansfield Avatar answered Nov 12 '22 10:11

Joseph Mansfield