同一頭文件 funcs.h,經由不同巨集定義多次 #include,產生不同程式碼片段(如枚舉值、函數宣告、字串表)。
/* funcs.h */ FUNC_1(ID_FUN1_001) FUNC_1(ID_FUN1_002) FUNC_2(ID_FUN2_001) FUNC_2(ID_FUN2_002)
#define FUNC_1(opt) opt,
#define FUNC_2(opt) // 空
enum aaa {
#include "funcs.h"
ID_FUN1_END
};
#undef FUNC_1
#undef FUNC_2
展開後:
enum aaa {
ID_FUN1_001,
ID_FUN1_002,
ID_FUN1_END
};
#define FUNC_1(opt) // 空
#define FUNC_2(opt) opt,
enum bbb {
#include "funcs.h"
ID_FUN2_END
};
#undef FUNC_1
#undef FUNC_2
展開後:
enum bbb {
ID_FUN2_001,
ID_FUN2_002,
ID_FUN2_END
};
#include 前重新定義巨集行為。#undef 清理,避免汙染後續編譯。/ * ops.def * /
OP(ADD, "+")
OP(SUB, "-")
OP(MUL, "*")
OP(DIV, "/")
/ * 使用 * /
#define OP(name, sym) name,
typedef enum { #include "ops.def" } OpCode;
#undef OP
#define OP(name, sym) sym,
const char *op_str[] = { #include "ops.def" };
#undef OP