Stats

420 Contributors: 11 Saturday, February 25, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

X-macros

Introduction

X-macros are a preprocessor-based technique for minimizing repetitious code and maintaining data / code correspondences. Multiple distinct macro expansions based on a common set of data are supported by representing the whole group of expansions via a single master macro, with that macro's replacement text consisting of a sequence of expansions of an inner macro, one for each datum. The inner macro is traditionally named X(), hence the name of the technique.

Remarks

The user of an X-macro-style master macro is expected to provide his own definition for the inner X() macro, and within its scope to expand the master macro. The master's inner macro references are thus expanded according to the user's definition of X(). In this way, the amount of repetitive boilerplate code in the source file can be reduced (appearing only once, in the replacement text of X()), as is favored by adherents to the "Do not Repeat Yourself" (DRY) philosophy.

Additionally, by redefining X() and expanding the master macro one or more additional times, X macros can facilitate maintaining corresponding data and code -- one expansion of the macro declares the data (as array elements or enum members, for example), and the other expansions produce corresponding code.

Although the "X-macro" name comes from the traditional name of the inner macro, the technique does not depend on that particular name. Any valid macro name can be used in its place.

Criticisms include

  • source files that rely on X macros are more difficult to read;
  • like all macros, X macros are strictly textual -- they do not inherently provide any type safety; and
  • X macros provide for code generation. As compared to alternatives based on calling functions, X macros effectively make the code larger.

A good explanation of X macros can be found in Randy Meyers' article [X-Macros] in Dr. Dobbs (http://www.drdobbs.com/the-new-c-x-macros/184401387).

Related Examples