C 有人能用使用X宏的示例代码解释一下吗?
我试图详细理解X宏主题。但这件事还没有完全弄清楚。如果任何一位专家都能用“如何使用,如何调用”的例子来解释这个主题,那就更好了 我找到了好几篇文章,但没有完全弄清楚这一点。在所有地方,他们都使用了我在使用X宏方面所缺乏的代码片段 提前谢谢 Partha您基本上C 有人能用使用X宏的示例代码解释一下吗?,c,macros,x-macros,C,Macros,X Macros,我试图详细理解X宏主题。但这件事还没有完全弄清楚。如果任何一位专家都能用“如何使用,如何调用”的例子来解释这个主题,那就更好了 我找到了好几篇文章,但没有完全弄清楚这一点。在所有地方,他们都使用了我在使用X宏方面所缺乏的代码片段 提前谢谢 Partha您基本上#定义一个变量列表作为占位符宏的参数X: #define X_LIST_OF_VARS \ X(my_first_var) \ X(another_variable) \ X(and_another_one) 然后
#定义一个变量列表作为占位符宏的参数X
:
#define X_LIST_OF_VARS \
X(my_first_var) \
X(another_variable) \
X(and_another_one)
然后使用模板:
#define X(var) do something with var ...
X_LIST_OF_VARS
#undefine X
制作代码块。例如,要打印所有变量,请执行以下操作:
#define X(var) printf("%d\n", var);
X_LIST_OF_VARS
#undefine X
将产生:
printf("%d\n", my_first_var);
printf("%d\n", another_variable);
printf("%d\n", and_another_one);
其思想是重新定义宏X,使数据符合当前用途
您至少需要2个文件。第一个是一个包含必要信息的巨大表格,另一个是使用数据的表格
表x:
X("Human", 2, HUMAN)
X("Spider", 8, SPIDER)
// 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
};
模块c:
X("Human", 2, HUMAN)
X("Spider", 8, SPIDER)
// 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
};
预处理的输出将是:
// 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",
};
在上面的示例中,很容易向表中添加新项。如果单独管理这些列表,则更容易出错
编辑:
X("Human", 2, HUMAN)
X("Spider", 8, SPIDER)
// 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
};
关于宏用法的一些说明
在第一行#定义X(描述、支腿、id)支腿,
我们定义X
宏。宏的参数数必须与表.x的每行参数数相同。对于这种用法,我们只对legs
参数感兴趣。请注意,参数名称是没有意义的,我们还可以定义X(a,b,c)b,
第二行#include“table.x”
包括table.x
到module.c
的内容。由于宏X
已经定义,预处理器通过调用X
对每一行进行文本替换
第三行#undef X
仅为方便起见。我们删除了X
的定义,这样以后就可以重新定义它,而不需要编译器发出警告。如果您不使用我的定义,请您解释一下上面示例中使用的代码#定义(描述、支腿、id)支腿,#包括“table.x”#未定义X@user1537070查看我的编辑。@user694733我看不出使用2个文件的原因。我可以知道你为什么说至少要使用2个文件吗?@nomanguigt正如其他答案所示,只能使用一个文件。对于2文件方法,最大行长度的问题较少,但对于现代编译器来说,这已经不是什么大问题了。