简体   繁体   English

在循环中串联c中的宏

[英]concatenate macros in c in a loop

i want to concatenate a lot of macros in order to pass them as parameter in a struck array. 我想连接很多宏,以便将它们作为参数传递给被击中的数组。 to be more specific i have this struct 更具体地说,我有这个结构

static struct
{
 unsigned int num_irqs;
 volatile __int_handler *_int_line_handler_table;
}_int_handler_table[INTR_GROUPS];

and I want to pass as num_irqs parameter a series of macros 我想将一系列宏作为num_irqs参数传递

AVR32_INTC_NUM_IRQS_PER_GRP1

AVR32_INTC_NUM_IRQS_PER_GRP2
...

first I thought to use this code 首先我想使用此代码

for (int i=0;i<INTR_GROUPS;i++)
{
   _int_handler_table[i].num_irqs = TPASTE2(AVR32_INTC_NUM_IRQS_PER_GRP,i); 
}

but it takes the i as char and not the specific value each time. 但每次都将i当作char而不是特定值。 I saw also that there is a MREPEAT macro defined in the preprocessor.h but I do not understand how it is used from the examples. 我还看到在preprocessor.h中定义了一个MREPEAT宏,但是我不理解如何从示例中使用它。

Can anyone can explain the use of MREPEAT or another way to do the above. 任何人都可以解释使用MREPEAT或进行上述操作的其他方式。

C doesn't work like that. C不能那样工作。

Macros are just text-replacement which happens att compile-time. 宏只是在编译时发生的文本替换。 You can't write code to construct a macro name, that doesn't make sense. 您无法编写代码来构造宏名称,这没有任何意义。 The compiler is no longer around when your code runs. 运行代码时,编译器不再存在。

You probably should just do it manually, unless the amount of code is very large (in which case code-generation is a common solution). 除非代码量很大(在这种情况下,代码生成是一种常见的解决方案),否则您可能应该只手动执行此操作。

Keep in mind the preprocessor (which manipulates macros) runs before the compiler. 请记住,预处理器(用于处理宏) 编译器之前运行。 It's meant to manipulate the final source code to be submitted to the compiler. 这意味着要操纵最终的源代码以提交给编译器。

Hence, it has no idea of what value has a variable. 因此,它不知道什么值具有变量。 For the preprocessor, i means i . 对于预处理器, i表示i

What you try to do is a bit complex, especially keeping in mind that preprocessor cannot generate preprocessor directives. 您尝试执行的操作有些复杂,尤其要记住预处理器无法生成预处理器指令。

But it can generate constants. 但是它可以生成常量。 Speaking of which, for your use case, I would prefer to use a table of constants, such as : 说到这,对于您的用例,我更喜欢使用常量表,例如:

const int AVR32_INTC_NUM_IRQS_PER_GRP[] = { 1, 2, 3, 4, 5 };

for (int i=0;i<INTR_GROUPS;i++)
{
   _int_handler_table[i].num_irqs = TPASTE2(AVR32_INTC_NUM_IRQS_PER_GRP[i]); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM