【分类】c语言宏-宏的妙用
【摘要】受tcc-0.9.24源码启发,宏的巧妙应用
<引用tcc源码,为了方便说明问题,删减了大部分代码>
注:Tiny C Compiler(TCC) 是一个轻量级高速的C语言编译器,开源。
// tcc.c
/* only used for i386 asm opcodes definitions */
#define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
#define DEF_BWL(x) \
DEF(TOK_ASM_ ## x ## b, #x "b") \
DEF(TOK_ASM_ ## x ## w, #x "w") \
DEF(TOK_ASM_ ## x ## l, #x "l") \
DEF(TOK_ASM_ ## x, #x)
#define TOK_ASM_int TOK_INT
enum tcc_token {
TOK_LAST = TOK_IDENT - 1,
#define DEF(id, str) id,
#include "tcctok.h"
#undef DEF
};
static const char tcc_keywords[] =
#define DEF(id, str) str "\0"
#include "tcctok.h"
#undef DEF
;
// tcctok.h
/* keywords */
DEF(TOK_INT, "int")
DEF(TOK_VOID, "void")
DEF(TOK_CHAR, "char")
/* preprocessor only */
DEF(TOK_DEFINE, "define")
DEF(TOK_INCLUDE, "include")
DEF(TOK_INCLUDE_NEXT, "include_next")
/* Tiny Assembler */
DEF_ASM(byte)
DEF_ASM(align)
DEF_ASM(skip)
/* generic two operands */
DEF_BWL(add)
DEF_BWL(or)
DEF_BWL(adc)
<引用结束>
enum tcc_token {
TOK_LAST = TOK_IDENT - 1,
#define DEF(id, str) id,
#include "tcctok.h"
#undef DEF
};
static const char tcc_keywords[] =
#define DEF(id, str) str "\0"
#include "tcctok.h"
#undef DEF
首先枚举定义了tcc用到的token,然后再进行对应字符串的储存,十分巧妙。
DEF_ASM(byte)相当于
DEF(TOK_ASM_byte, "byte")
DEF_BWL(add)相当于
DEF(TOK_ASM_addb, "addb") \
DEF(TOK_ASM_addw, "addw") \
DEF(TOK_ASM_addl, "addl") \
DEF(TOK_ASM_add, "add")
利用宏实现了复用,也减轻了程序员的工作,这大概也是tcc小巧的原因吧!