c語言宏的妙用--大量字符聲明

 
【分類】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小巧的原因吧!
 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章