C语言 宏/macor/#define/

C语言 宏/macor/#define 高级技巧

1、在进行调试的时候,需要进行打印/PRINT,可以通过define进行自定义。例如,自己最常用的DEBUG_PRINT()

#define     DEBUG                                 1
//#undef      DEBUG
#if DEBUG
    #define DEBUG_PRINT(fmt, args...) fprintf(stdout, fmt"\tDEBUG: %s:%d:%s\n",  ##args, __FILE__,  __LINE__, __func__)
#else
    #define DEBUG_PRINT(fmt, args...)
#endif

这是一个variable arguments的printf,可以像使用库函数一样使用DEBUG_PRINT()。

2、Pasting Tokens/粘贴token/将token和在...上

Each argument passed to a macro is a token, and sometimes it might be expedient to paste arguments together to form a new token. This could come in handy if you have a complicated structure and you'd like to debug your program by printing out different fields. Instead of writing out the whole structure each time, you might use a macro to pass in the field of the structure to print.

To paste tokens in a macro, use ## between the two things to paste together.

For instance

#define BUILD_FIELD(field) my_struct.inner_struct.union_a.##field

Now, when used with a particular field name, it will expand to something like

my_struct.inner_struct.union_a.field1

The tokens are literally pasted together.

3、String-izing Tokens/将token/标志/参数转化为字符串

Another potentially useful macro option is to turn a token into a string containing the literal text of the token. This might be useful for printing out the token. The syntax is simple--simply prefix the token with a pound sign (#).

#define PRINT_TOKEN(token) printf(#token " is %d", token)

For instance,PRINT_TOKEN(foo) would expand to

printf("<foo>" " is %d" <foo>)

(Note that in C, string literals next to each other are concatenated, so something like "token" " is " " this " will effectively become "token is this". This can be useful for formatting printf statements.)

For instance, you might use it to print the value of an expression as well as the expression itself (for debugging purposes).

PRINT_TOKEN(x + y);

参考:
1、The C Preprocessor
2、Preprocessor directives

转载于:https://www.cnblogs.com/xuanyuanchen/p/6023488.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值