user11222840
user11222840

Reputation:

Preprocessing string concatenation

I would like to concatenate the 3 following strings to produce a good debug output, by using std::setw() after.

__ FILENAME__ , ":" and LINE

#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)

#define AT __FILENAME__ ":" __LINE__

#ifdef DEBUG
    #ifdef VERBOSE
       #define printDebug(x) std::cout << AT << x << std::flush
    #else
       #define printDebug(x) std::cout << x << std::flush
    #endif
#else
    #define printDebug(x)
#endif

But actually I receive errors saying that a ";" field is missing before ":". Does someone have an idea ?

I actually call the printDebug() function like that :

printDebug("[SUCCESS] Receiving Message");

Upvotes: 0

Views: 114

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96811

You can concatenate string literals by putting them alongside each other.

":" is a string literal.

__LINE__ expands to a numeric literal, not string one.

__FILENAME__ doesn't expand to a literal at all. It expands to an expression.

There is a way to get a string literal out of __LINE__, but you can't make __FILENAME__ a string literal.


You don't need to use literal concatenation here at all. You can simply do this:

#ifdef VERBOSE
#define printDebug(x) std::cout << __FILENAME__ << ":" << __LINE__ << x << std::flush

Upvotes: 2

Related Questions