c++macros

Token pasting and __LINE__


I'm writing a simple macro to show TRACE information.

This is what I'm using ,

#ifdef __DEBUG__
#define TRACE  { PrintErrorMsg("Trace exception at " __FILE__  "LineNo:"##(__LINE__) "Function: " __FUNCTION__ " " );}
#else 
#define TRACE 
#endif

This is working with __FILE__, but it doesn't seems to work with __LINE__.
Any idea how could I deal with this. I already tried stringing operator too. Which is as bellow

#ifdef __DEBUG__
#define TRACE  { PrintErrorMsg("Trace exception at " __FILE__  "LineNo:"#(__LINE__) "Function: " __FUNCTION__ " " );}
#else 
#define TRACE 
#endif

and without parms and with double parms , ex - __LINE__ or ((__LINE__)) Any idea how could I deal with this problem?

And I come up with this,

#ifdef __DEBUG__
#define ERROR_MSG_BUF_SIZE 1024
#define TRACE  { char * error_msg_buffer = new char[ERROR_MSG_BUF_SIZE]; \
    sprintf(error_msg_buffer,"Trace Exception at file: %s ,Line : %d , Function %s \n",__FILE__,__LINE__,__FUNCTION__);\
    PrintErrorMsg(error_msg_buffer );\
    delete[] error_msg_buffer;}
#else 
#define TRACE
#endif

But I want to do it without using sprintf, just only by stringing and token pasting.


Solution

  • You need this kind of silliness, unfortunately.

    #include <stdio.h>
    
    #define TRACE2(f,l) printf("I am at file: " f " and line: " #l "\n")
    #define TRACE1(f,l) TRACE2(f,l)
    #define TRACE() TRACE1(__FILE__, __LINE__)
    
    int main(void)
    {
        TRACE();
        TRACE();
    }
    

    I am at file: test.cpp and line: 9
    I am at file: test.cpp and line: 10