C语言 宏/macor/#define 高级技巧
1、在进行调试的时候,需要进行打印/PRINT,可以通过define进行自定义。例如,自己最常用的DEBUG_PRINT()
#define DEBUG 1
//#undef DEBUG
#if DEBUG
#define DEBUG_PRINT(fmt, args...) fprintf(stdout, fmt" DEBUG: %s:%d:%s
", ##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);