1. ##: 將前後兩個的單詞拼接在一起
#define show_port(portname) show_##portname
調用show_port(mac0)展開後成為show_mac0
2. 程式範例
#include <stdio.h>
#define show_port(portname, port) \
static void show_##portname() \
{ \
int val = 0; \
val |= port; \
printf("port = %s, ", #portname); \
printf("val = 0x%04x\n", val); \
}
show_port(mac0, 0);
show_port(mac1, 1);
show_port(cpu, 2);
int main(int argc, char *argv[])
{
show_mac0();
show_mac1();
show_cpu();
return 0;
}
執行結果:
port = mac0, val = 0x0000
port = mac1, val = 0x0001
port = cpu, val = 0x0002
3. Macro展開後
show_port(mac0, 0);展開後
static void show_mac0()
{
int val = 0;
val |= 0;
printf("port = %s, ", "mac0");
printf("val = 0x%04x\n", val);
}
}
show_port(mac1, 1);展開後
static void show_mac1()
{
int val = 0;
val |= 1;
printf("port = %s, ", "mac0");
printf("val = 0x%04x\n", val);
}
}
show_port(cpu, 2);展開後
static void show_cpu()
{
int val = 0;
val |= 2;
printf("port = %s, ", "cpu");
printf("val = 0x%04x\n", val);
}