0

I have been doing a task to change the current logging mechanism in my CPP codebase.

The current one is something like a printf in which we can write

MYLOGGING(("Example Log :%s, Example Num: %d", String, Number));

Now as part of modifying it to the new logging mechanism, I want to get this complete output to a string using the snprintf(). For that I used a variable list for this.

The code was like

#define MYLOGGING(log_string,...) do { \
char buff[1024]; \
memset(buff, 0, sizeof(buff)); \
snprintf(buff, sizeof(buff), log_string, ##__VA_ARGS__); \
MYNEW_LOG(NewlogParams, buff); \
} while(0)

Now, I am facing an issue. The existing logging had many instances in which some enum values are printed using simple %d. In such cases, with this new code, it is throwing the following error.

error: cannot convert ‘enumType’ to ‘const char*’ for argument ‘3’ to ‘int snprintf(char*, size_t, const char*, ...)’

One obvious option to get rid of this is to give integer type casting for enum prints.

As that could be a tedious process, i am curious to know whether I can fix this in some other way?

Please share your views.

Thanks in advance.

0

1 Answer 1

2

By appending the ## operator to the __VA_ARGS__, you are turning the format parameters into a const char *:

snprintf(buff, sizeof(buff), log_string, ##__VA_ARGS__);

Change that to:

snprintf(buff, sizeof(buff), log_string, __VA_ARGS__);

and the conversion should work.


Actually, after looking at your question more carefully, I've noticed another problem. The ## operator is indeed unusual and probably incorrect, however, the main cause of your problem seems to be the extra parens in the call to MYLOGGING

MYLOGGING(("Example Log :%s, Example Num: %d", String, Number));

If you compile a call to that macro in GCC with the -E flag to output the preprocessed source, you'll get this line expanded from the macro:

do { char buff[1024]; memset(buff, 0, sizeof(buff)); snprintf(buff, sizeof(buff), ("Example Log :%s, Example Num: %d", String, Number)); ....

You can see that the () are still there, messing up the call to snprintf. So remove both ## in the macro and the extra parens in the call site.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you glampert. Things are fine when i changed it to snprintf(buff, sizeof(buff), "log_string",## VA_ARGS); Now i have a confusion what is the diff between my old code and the one with "" for log_string. Could you give an answer?
Read about the token concatenation operator: gcc.gnu.org/onlinedocs/cpp/Concatenation.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.