Stringification of the __LINE__ macro

P

pistmaster

Hi,

I am trying the use the current line number in my logging and I want
to stringify it so that I know the size of the buffer required to
output the log string. I would have though I could use #__LINE__ in a
macro like:

#define LOG_ERROR(err) LogError(err, __FILE__, #__LINE__)

but all i get in the output is #<linenumber>. Why should this be?
And is there another way to accomplish what i am trying to do.

Thanks
 
S

santosh

Hi,

I am trying the use the current line number in my logging and I want
to stringify it so that I know the size of the buffer required to
output the log string. I would have though I could use #__LINE__ in a
macro like:

#define LOG_ERROR(err) LogError(err, __FILE__, #__LINE__)

but all i get in the output is #<linenumber>. Why should this be?
And is there another way to accomplish what i am trying to do.

Thanks

Try this:

#include <stdio.h>

#define strfy(line) #line
#define LOG_ERROR(err, file, line) LogError(err, file, (strfy(line)))

void LogError(int, char *, char *);

int main(void) {
LOG_ERROR(2, __FILE__, __LINE__);
return 0;
}

void LogError(int err, char *f, char *l) {
fprintf(stderr, "err = %d\tfile = %s\tline = %s\n", err, f, l);
return;
}
 
P

pistmaster

Try this:

#include <stdio.h>

#define strfy(line) #line
#define LOG_ERROR(err, file, line) LogError(err, file, (strfy(line)))

void LogError(int, char *, char *);

int main(void) {
LOG_ERROR(2, __FILE__, __LINE__);
return 0;

}

void LogError(int err, char *f, char *l) {
fprintf(stderr, "err = %d\tfile = %s\tline = %s\n", err, f, l);
return;

}

Yes that works thanks :)
 
R

Robert Gamble

Hi,

I am trying the use the current line number in my logging and I want
to stringify it so that I know the size of the buffer required to
output the log string. I would have though I could use #__LINE__ in a
macro like:

#define LOG_ERROR(err) LogError(err, __FILE__, #__LINE__)

but all i get in the output is #<linenumber>. Why should this be?
And is there another way to accomplish what i am trying to do.

The # operator can only be applied to a macro parameter, what you have
is not valid. Try this:

#define STRINGIFY(x) #x
#define LOG_ERROR(err) LOG_ERROR2(err, __FILE__, __LINE__)
#define LOG_ERROR2(err, file, line) LogError(err, file,
STRINGIFY(line))

Robert Gamble
 

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,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top