1

Is there an easy way to build a string which includes the _FILE_ and _LINE_ values?

I could do something like:

std::stringstream ss;
ss << "Error in "<<_FILE_<<":"<<_LINE_<<" - too many bees!";
log(ss.str());

But that is a PITA, compared to the ideal which might be:

log("Error in "+_FILE_+":"+_LINE_+" - too many bees!");

Is there a neat way to do this in C++/STL/boost? Note I am limited to older compiler, no C++11!

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • btw, should be `__FILE__` and `__LINE__` – billz Oct 16 '13 at 10:42
  • 2
    http://stackoverflow.com/questions/19343205/c-concatenating-file-and-line-macros – Alex F Oct 16 '13 at 10:42
  • I see questions with single and double underscores, also `_line` - do all versions exist or are people just lazy when typing? – Mr. Boy Oct 16 '13 at 10:43
  • @AlexFarber same basic question but no full answer (working code example is provided) If someone provides one to either question that would be ideal. – Mr. Boy Oct 16 '13 at 10:45
  • Mostly, people macroize their log calls to make this easy by baking in the boilerplate. – mah Oct 16 '13 at 10:48
  • 1
    @John which part of the log message do you need to be customizable? I doubt you want to keep typing `__FILE__` and `__LINE__` everytime you want to log something. – greatwolf Oct 16 '13 at 10:50
  • @AlexFarber I didn't believe I could use `+` to build a string in-place this way? – Mr. Boy Oct 16 '13 at 10:57

1 Answers1

2

As Alex commented: double macro expansion to make __LINE__ into a string and let the compiler concatenate the strings for you:

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

log("Error in "__FILE__":"S__LINE__" - too many bees!");

to reduce typing, as greatwolf suggested:

#define logfl(s) log("Error in "__FILE__":"S__LINE__" - "s)

logfl("too many bees!");
mark
  • 5,269
  • 2
  • 21
  • 34
  • 1
    I also find it quite useful to #define log to some function returning ostream&, then you can log all kind of objects there – Peter K Oct 16 '13 at 11:26