ant2009 ant2009 - 2 months ago 15
C Question

concatenating strings in a printf statement

gcc 4.7.2
c89


Hello,

#define LOG_ERR(fmt, ...) \
fprintf(stderr, "[ERROR] %s:%d: error [%s] " fmt "\n", __func__, __LINE__, strerror(errno), ##__VA_ARGS__)


And I am using it like this:

LOG_ERR("Failed to connect to message queue [ %d ]", msg_id);


The fmt has been concatenated in the fprintf statement. How is this possible?

I have tried to do the same with the following below just to test the concept, but failed with a compile error:

/* Using char array */
const char name[] = "Joe";

printf("Hello how " name " how are you today?\n");

Using constant string literal
const char *name = "Joe";

printf("Hello how " name " how are you today?\n");


Both game me the following error:

expected ')' before name


Many thanks for any suggestions,

Answer

When it fails, it's because you're using variables. String literals can be concatenated by the compiler i.e. if you write "abc" "123" then the compiler will treat this as "abc123". And when you do this in the macro, the preprocessor means that this is exactly what is sent to the compiler

LOG_ERR("Failed to connect to message queue [ %d ]", msg_id);

becomes

fprintf(stderr, "[ERROR] %s:%d: error [%s] " "Failed to connect to message queue [ %d ]" "\n", myfunction, 123, strerror(errno), msg_id);

Might be worth checking out the stringizer and concatenation macros too (for the preprocessor - # and ## and I never remember which is which...)

Andrew