Preprocessor: convert __LINE__ to const char*

T

Torsten Wiebesiek

Hi,

I have a problem with the preprocessor. I have written my own little
assert macro. This is supposed to log a message (with log4cxx):

#define LogAssert(Expression) \
if (Expression) { \
LOG4CXX_FATAL(log4cxx::Logger::getRootLogger(), "LogAssert: " \
#Expression " in file " __FILE__ ", line " #__LINE__ "."); \
::exit(1); \
}

Unfortunately, the preprocessor is only quoting marcro arguments. In my
case, Expression is quoted with #Expression. __LINE__ expands to an
integer literal. Is there an way to convert __LINE__ to a const char* at
compile time?

Thanks for you help,

Torsten
 
M

Marco Manfredini

Torsten said:
Hi,

I have a problem with the preprocessor. I have written my own little
assert macro. This is supposed to log a message (with log4cxx):

#define LogAssert(Expression) \
if (Expression) { \
LOG4CXX_FATAL(log4cxx::Logger::getRootLogger(), "LogAssert: " \
#Expression " in file " __FILE__ ", line " #__LINE__ "."); \
::exit(1); \
}

Unfortunately, the preprocessor is only quoting marcro arguments. In

So turn the expansion of __LINE__ into a macro argument.
#define STR2(X) #X
#define STR(X) STR2(X)
#define LOG(X) logger(X " happend here:" __FILE__ STR(__LINE__))

STR(X) expands __LINE__ to the actual line number, and STR2 does the
quoting.
 
T

Torsten Wiebesiek

I have a problem with the preprocessor. I have written my own little
So turn the expansion of __LINE__ into a macro argument.
#define STR2(X) #X
#define STR(X) STR2(X)
#define LOG(X) logger(X " happend here:" __FILE__ STR(__LINE__))

STR(X) expands __LINE__ to the actual line number, and STR2 does the
quoting.

Thanks, a lot and have a nice weekend. :)
 
R

red floyd

Just found the solution at an unexpected place :)http://en.wikipedia.org/wiki/C_preprocessor#Indirectly_quoting_macro_...

1: #define _QUOTE(x)  #x
2: #define QUOTE(x)  _QUOTE(x)
3:
4: _QUOTE(__LINE__)    // expands to "__LINE__"
5: QUOTE(__LINE__)     // expands to "5"

This is bad. Identifiers with leading underscore followed by an
uppercase letter are reserved to the implementation. That is, your
implementation may be using _QUOTE for its own purposes.

Either use a trailing underscore, or some other convention (i.e.
QUOTE_() or QUOTE2()).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top