简体   繁体   中英

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");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM