A basic definition and example and a few references for ‘X-Macros‘ is given in this wikipedia entry on the C pre-processor:
An X-Macro is a header file (commonly using a ‘.def’ extension instead of the traditional ‘.h’) that contains a list of similar macro calls (which can be referred to as ‘component macros’).
What are some good sources of information on how to use this powerful technique? Are there well-known open source libraries using this method?
I use X Macros() in code a lot. The value comes from only adding new data only to the ‘X list’ and not modifying any other code.
The most common use of X Macros() is for associating error text with error codes. When new error codes are added, programmers must remember to add the code and the text, typically in separate places. The X Macro allows the new error data to be added in a single place and get automatically populated anywhere it is needed.
Unfortunately, the mechanisms use a lot of pre-compiler magic that can make the code somewhat hard to read (e.g. string joining with
token1##token2, string creation with#token). Because of this I typically explain what the X Macro is doing in the comments.Here is an example using the error/return values. All new data gets added to the ‘
X_ERROR‘ list. None of the other code hast to be modified.You can also use X Macros() to generate code. For example to test if an error value is ‘known’, the X Macro can generate cases in a switch statement: