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小巧的原因吧!
 
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值