</>EmbeddedInterview

What are # and ## in macros?

MediumC Programming

Short answer: # (the stringizing operator) turns a macro argument into a string literal. ## (the token-pasting operator) joins two tokens into one. They let macros generate names and strings automatically.

#define STR(x)     #x
#define XSTR(x)    STR(x)          /* two-level trick: expand x first */
#define REG(port)  GPIO##port##_ODR

STR(UART1)                         /* "UART1" */
REG(A)                             /* GPIOA_ODR */

#define VERSION 3
STR(VERSION)                       /* "VERSION"  - argument not expanded */
XSTR(VERSION)                      /* "3"        - expanded first, then stringized */

Why the two-level trick is needed: an argument used with # or ## is not macro-expanded first. Passing it through another macro (XSTR) expands it before it reaches #.

Practical uses

  • Assert and log messages that show the failed expression: #define ASSERT(e) do { if (!(e)) fail(#e, __FILE__, __LINE__); } while (0).
  • X-macros that keep an enum and its string names in sync:
#define STATES(X) X(IDLE) X(RUN) X(ERROR)
#define AS_ENUM(n)   ST_##n,
#define AS_STRING(n) #n,

enum state { STATES(AS_ENUM) ST_COUNT };
static const char *const state_name[] = { STATES(AS_STRING) };
/* ST_IDLE, ST_RUN, ST_ERROR and "IDLE", "RUN", "ERROR" from one list */
  • Generating register or handler names: #define IRQ_HANDLER(n) void n##_IRQHandler(void).
  • Embedding the firmware version string: const char fw_version[] = XSTR(MAJOR) "." XSTR(MINOR);

Rules: the result of ## must be a valid single token (pasting + and / is undefined), and # escapes quotes and backslashes in the argument.