zoukankan      html  css  js  c++  java
  • 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"	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);
    

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

  • 相关阅读:
    【转】高性能网络编程4--TCP连接的关闭
    Kubernetes 用了,延迟高了 10 倍,问题在哪?
    多路复用和多路分用
    网络七层模型与四层模型区别
    Go验证包出错 dial tcp 34.64.4.17:443: i/o timeout
    spring Bean配置的三种形式
    Spring容器IOC初始化过程
    Go 特殊语法
    服务发现的基本原理与比较:Eureka vs Consul vs Zookeeper
    docker 常用命令
  • 原文地址:https://www.cnblogs.com/xuanyuanchen/p/6023488.html
Copyright © 2011-2022 走看看