Sign in to follow this  
cpp forever

[C++] concatenating __LINE__ in macro

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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__))

Share this post


Link to post
Share on other sites
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__)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this