Yuan Cao
Yuan Cao

Reputation: 25

I don't understand C macros

How does the LOG_FORMAT expand in esp_log_write? What does the format LOG_RESET_COLOR do in the LOG_FORMAT?

 #define LOG_FORMAT(letter, format)  LOG_COLOR_ ## letter #letter " (%d) %s: " format LOG_RESET_COLOR "\n"

 esp_log_write(ESP_LOG_VERBOSE, tag, LOG_FORMAT(V, format), esp_log_timestamp(), tag, ##__VA_ARGS__); }


void esp_log_write(esp_log_level_t level,
                   const char *tag,
                   const char *format, ...)
{
    va_list arg;
    va_start(arg, format);
    vprintf(format, arg);
    va_end(arg);
}

Upvotes: 2

Views: 175

Answers (1)

Serge
Serge

Reputation: 12384

In macro expansion ## means concatenation of any text with a macro argument. # means that the macro argument which follows it will be placed in double quotes.

Now, in 'C' neighboring string literals, separated just by spaces really means a concatenation of 2 strings, i.e. "hello " "world" really means "hello world"

So, macro LOG_FORMAT(V, format) gets expanded to

LOG_COLOR_V "V" " (%d) %s: " format LOG_RESET_COLOR "\n" 

now, the above by itself is not a legal 'C' syntax. So, most likely there are also definitions for LOG_COLOR_V, format, and LOG_RESET_COLOR. They are supposed to be defined as quoted strings themselves. In this case all the above will be interpreted as a single quoted string.

Upvotes: 1

Related Questions