替换宏变量中的字符串? [英] Replace a string in a macro variable?
问题描述
我有一个宏,我可以在该宏中传递参数,并使用该宏根据输入的名称定义一个新变量:
I have a macro where I pass in an argument and use that define a new variable based on the name of the input:
#define DO_X(x) char _do_x_var_ ## x; /* other things */
问题是,如果我传入一个struct变量,它会中断:
The problem is if I pass in a struct variable, it breaks:
DO_X(some_struct->thing)
成为:
char _do_x_var_some_struct->thing; /* other things */
我希望它评估为:
char _do_x_var_some_struct__thing; /* other things */
(或任何与输入内容相似的有效变量名)
(or any valid variable name containing something similar to the input)
我真正想要的是使它们起作用:
What I actually want is for these to work:
#define DO_X(x) for(char _do_x_var_ ## x; /*things*/)
DO_X(x){
DO_X(y) {
/*things*/
}
}
DO_X(object->x){
DO_X(object->y) {
/*things*/
}
}
但是这些失败了:
#define DO_X(x) for(char _do_x_var_ ## x; /*things*/)
DO_X(x){
DO_X(x) { // <-- multiple definition of _do_x_var_x
/*things*/
}
}
DO_X(object->x){
DO_X(object->x) { // <-- multiple definition of _do_x_var_object__x (or whatever)
/*things*/
}
}
有什么办法可以使这项工作成功吗?也许用__
替换->
或其他?我找到了串联的方法,但没有替换字符串的方法.
Is there some way to make this work? Maybe replacing ->
with __
or something? I've found ways to concatenate, but not replace strings..
推荐答案
您尚未找到重写任意字符串的方法,因为宏无法做到这一点.宏名称必须是有效的标识符,而->
则不是. C预处理器的功能非常有限.您可以研究m4
以获得更强大的预处理器,但您可能走错了路.
You haven't found a way to rewrite arbitrary strings because macros cannot do that. Macros names have to be valid identifiers, which ->
is not. The C preprocessor is very limited in what it can do. You could look into m4
for a stronger preprocessor, but you're likely headed down the wrong road.
这篇关于替换宏变量中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!