[C++] concatenating __LINE__ in macro

Started by
5 comments, last by LessBread 18 years, 6 months ago
I want to concatenate __LINE__ with __FILE__ and other text. I'm having a compiler error, cos __LINE__ is integer.

 #define MO_DEBUG(str__)         {char c__[16]; ltoa(__LINE__, c__, 10); (OutputDebugString(TEXT(__FILE__##"("##(c__)##")"##" : "##str__##".\n"))); }


How do I made this? And I hope its possible...
ai-blog.org: AI is discussed here.
Advertisement
If I'm understanding your problem correctly you can just put a # in front of __LINE__ to stringify it. I doesn't have MSVC on this machine so cant test if you have to do something else too.
Check the documentation for the compiler that you're using. Chances are that the __LINE__ token requires specific debug settings to operate as expected.

...

Looking closer at that macro, I don't think the preprocessor will treat the string variable c__ as a string literal. You might consider using sprintf or similar, along these lines:

sprintf(buffer, "%s %d %s\n", __FILE__, __LINE__, str__); OutputDebugString(buffer);

// edit - CTar's approach is better than using sprintf and Fruny's is better than that
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
CTar - #__LINE__ will produce "__LINE__", not "42" or whatever. You need to do something as I do below in STR() to produce "42".


Try:

#define STR2(X) #X#define STR(X) STR2(X)#define CAT2(X,Y) X##Y#define CAT(X,Y) CAT2(X,Y)CAT(STR(__LINE__),STR(__FILE__))
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
As has been pointed out there are several problems with that macro. Another is that you're doing something that complicated in a macro in the first place. Better to have a simple macro that bounces stuff to a different function, e.g.:

#define MO_DEBUG(str__)         Trace(__LINE__, __FILE__, str__)
-Mike
Quote:Original post by LessBread
sprintf(buffer, "%s %d %s\n", __FILE__, __LINE__, str__); OutputDebugString(buffer);

Crazy me. How I didn't make that!:-)
ai-blog.org: AI is discussed here.
Quote:Original post by cpp forever
Quote:Original post by LessBread
sprintf(buffer, "%s %d %s\n", __FILE__, __LINE__, str__); OutputDebugString(buffer);

Crazy me. How I didn't make that!:-)


Don't discount Fruny or Anon Mike's comments.

OutputDebugString(CAT(STR(__LINE__),STR(__FILE__)))

might do the trick as well.
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man

This topic is closed to new replies.

Advertisement