Real-world use of X-Macros

前端 未结 7 1121
花落未央
花落未央 2020-11-22 12:21

I just learned of X-Macros. What real-world uses of X-Macros have you seen? When are they the right tool for the job?

相关标签:
7条回答
  • 2020-11-22 12:46

    Some real-world uses of X-Macros by popular and large projects:

    Java HotSpot

    In the Oracle HotSpot Virtual Machine for the Java® Programming Language, there is the file globals.hpp, which uses the RUNTIME_FLAGS in that way.

    See the source code:

    • JDK 7
    • JDK 8
    • JDK 9

    Chromium

    The list of network errors in net_error_list.h is a long, long list of macro expansions of this form:

    NET_ERROR(IO_PENDING, -1)
    

    It is used by net_errors.h from the same directory:

    enum Error {
      OK = 0,
    
    #define NET_ERROR(label, value) ERR_ ## label = value,
    #include "net/base/net_error_list.h"
    #undef NET_ERROR
    };
    

    The result of this preprocessor magic is:

    enum Error {
      OK = 0,
      ERR_IO_PENDING = -1,
    };
    

    What I don't like about this particular use is that the name of the constant is created dynamically by adding the ERR_. In this example, NET_ERROR(IO_PENDING, -100) defines the constant ERR_IO_PENDING.

    Using a simple text search for ERR_IO_PENDING, it is not possible to see where this constant it defined. Instead, to find the definition, one has to search for IO_PENDING. This makes the code hard to navigate and therefore adds to the obfuscation of the whole code base.

    0 讨论(0)
提交回复
热议问题