1

In a few C programs (for example in gecko) I've noticed an idiom whereby a program will temporarily define a macro, then include a file which uses that macro, then undefine the macro. Here's a trivial example:

speak.c:

#define SPEAK(phrase) (printf("When I speak I say %s\n", (phrase)))
#include "dog.h"
#undef SPEAK

dog.h:

SPEAK("woof");

Which expands to:

(printf("When I speak I say %s\n", ("woof")))

I gather this might be a useful technique to generalize included code by being able to specify behavior at the expansion site.

Does this pattern have a name, or has it been written about previously?

user12341234
  • 6,573
  • 6
  • 23
  • 48
  • Pretty strange to use non-compiling code as an example, there's no `;` after the statement (and a statement in `()` makes little sense to me). – unwind Dec 06 '17 at 14:32
  • 2
    This is close/identical to the [X macro](https://en.wikipedia.org/wiki/X_Macro) concept. – Oliver Charlesworth Dec 06 '17 at 14:32
  • 1
    @OliverCharlesworth IMO that comment is answer worthy! – user12341234 Dec 06 '17 at 14:34
  • Possible duplicate of [What is a good reference documenting patterns of use of X-Macros in C (or possibly C++)?](https://stackoverflow.com/questions/264269/what-is-a-good-reference-documenting-patterns-of-use-of-x-macros-in-c-or-possib), and there's also [Real-world use of X-Macros](https://stackoverflow.com/questions/6635851/real-world-use-of-x-macros) – underscore_d Dec 06 '17 at 14:36

1 Answers1

4

This is a variant of what are often called X macros.

Further reading

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680