For example, if you want to design a message processing module in the code, the code should be as concise as possible and scalable. Might as well try the X_MACRO technique.
/*
设计一个消息处理的模块,收到消息调用对应的处理函数
*/
#include <stdio.h>
// 消息表定义,后续增加消息类型,只需在这里增加一行,并增加对应的处理函数即可
#define MACROS_TABLE \
X_MACROS(MSG1, msg1_process) \
X_MACROS(MSG2, msg2_process) \
X_MACROS(MSG3, msg3_process) \
// 消息枚举定义
typedef enum {
#define X_MACROS(a, b) a,
MACROS_TABLE
#undef X_MACROS
MSG_MAX
} MSG_TYPE;
// 消息类型字符串定义
const char *msg_str[] = {
#define X_MACROS(a, b) #a,
MACROS_TABLE
#undef X_MACROS
};
// 处理函数原型定义
typedef void (*func)(void *p);
static void msg1_process(void *p) {
printf("%s\n", (char *)p);
}
static void msg2_process(void *p) {
printf("%s\n",(char *)p);
}
static void msg3_process(void *p) {
printf("%s\n",(char *)p);
}
// 后续在上面添加处理函数
// 处理函数表
const func func_table[] = {
#define X_MACROS(a, b) b,
MACROS_TABLE
#undef X_MACROS
};
static void msg_handle(MSG_TYPE msg) {
if (msg < MSG_MAX) {
func_table[msg]((void *)msg_str[msg]);
}
}
int main() {
msg_handle(MSG1);
msg_handle(MSG2);
msg_handle(MSG3);
return 0;
}