cc-preprocessorundef

I am a bit lost as to the meaning of this C preprocessor statement,


So, to start off, here's the code, with actual names switched for generic ones to limit confusion.

/* Get the list of Hotkey commands */
#define A_COMMANDS_MACRO(a, b, c, d) a = b ,
enum {
#include "commandsFile.def"
} ;
#undef  A_COMMANDS_MACRO

This is a snippet from some source code I have been looking over and considering forking as a way to familiarize myself with the intricacies of the C programming language. So, to my untrained eye, this appears to do nothing. To my brain, defining something and then immediately undefining it would seem to cancel each other out.

Obviously, I realize that I'm wrong. But why am I wrong?


Solution

  • What you see there is usually called X-MACRO. The technique consists in defining macros via #define, and then including a file that makes use of them with #include.

    As a very simple example, you could have a header (say myheader.h) that declared 2 functions in the form of:

    int foo(MYTYPE a, MYTYPE_PTR b);
    void bar(MYTYPE a, MYTYPE_PTR b);
    

    And then, in your code:

    #define MYTYPE int
    #define MYTYPE_PTR int*
    #include "myheader.h"
    #undef MYTYPE
    #undef MYTYPE_PTR
    

    The #undefs are sometimes in the included file as well.

    For more information, take a look at this Wikipedia link.