Can any one explain about X-macros with example code to use them? [closed]

狂风中的少年 提交于 2021-01-19 09:02:04

问题


I am trying to understand the X-macros topic in detail. But didn't get the full clarity on this. It would be better if any one of the expert will explain this topic with some example "how to use, how to call."

I have found several articles, but didn't get the full clarity on this. In all places, they have used pieces of code where i am lacking in using of those X-macros.

Thanks in advance Partha


回答1:


You basically #define a list of variables as parameters to an place holder macro X:

#define X_LIST_OF_VARS \
    X(my_first_var) \
    X(another_variable) \
    X(and_another_one)

You then use the template:

#define X(var) do something with var ...
X_LIST_OF_VARS
#undefine X

to make code blocks. For example to print all your vars:

#define X(var) printf("%d\n", var);
X_LIST_OF_VARS
#undefine X

will generate:

printf("%d\n", my_first_var);
printf("%d\n", another_variable);
printf("%d\n", and_another_one);



回答2:


Idea is that you redefine macro X to make data fit your current purpose.

You need at least 2 files. First is a huge table with necessary information, and others where data is used.

table.x:

X("Human",  2, HUMAN)
X("Spider", 8, SPIDER)

module.c:

// ID constants
enum {
#define X(description, legs, id) id,
#include "table.x"
#undef X
    COUNT   // Last element is total number of elements
};

// Leg array
int NumberOfLegs [] = {
#define X(description, legs, id) legs,
#include "table.x"
#undef X
};

// Description array
const char * Descriptions [] = {
#define X(description, legs, id) description,
#include "table.x"
#undef X
};

Preprocessed output would be:

// ID constants
enum {
    HUMAN,
    SPIDER,
    COUNT   // Last element is total number of elements
};

// Leg array
int NumberOfLegs [] = {
    2,
    8,
};

// Description array
const char * Descriptions [] = {
     "Human",
     "Spider",
};

In the above example it is easy to add new items to tables. If you managed those lists separately, it would be more easier to make an error.

Edit:

Some clarification on macro usage.

In first line #define X(description, legs, id) legs, we define X macro. Macro must have same number of arguments as our table.x has on each line. For this usage we are only interested on legs parameter. Note that argument names are meaningless, we could as well do #define X(a, b, c) b,.

Second line #include "table.x" includes contents of table.x to module.c. Because macro X has been defined, preprocessor does text replacement to each line with call to X.

Third line #undef X is only for convenience. We remove definition of X so it can be redifined later without compiler throwing warnings.



来源:https://stackoverflow.com/questions/19588442/can-any-one-explain-about-x-macros-with-example-code-to-use-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!