本文介绍了c中的宏数组-是否可能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以创建类似宏数组的内容.我已经实现了以下有效的代码:

I was wondering if it is possible to create something like an array of macros.I've implemented the following code which works:

struct led_cmds_
{
    ioport_pin_t *commands[LED_COUNT] ;
};
struct led_cmds_ the_led_cmd_ ;

void populate() {
    the_led_cmd_.commands[0] = SPECIFICPIN(0);
}

和主要内容:

int main(void)
{
    //.....
    populate();
    LED_On(the_led_cmd_.commands[0]);
}

SPECIFICPI​​N(x)的宏定义为:

#define SPECIFICPIN(X) (LED##X##_PIN)

我一直希望的是一种可以做这样的事情的方法:

What I was hoping for is a way to is a way to do something like this:

#define ioport_pin_t* ARR_LED[LED_COUNT] \
for (int j = 0; j < LED_COUNT; j++) ARR_LED[j] = SPECIFICPIN(j);

然后仅在我要使用特定的引脚时才需要调用以下内容

and then only need to call the following when I want to use the specific pin

LED_On(ARR_LED[some_number])

当我尝试这样做时,出现未声明的ARR_LED(此功能首次使用)错误.

when I try to do that I get an ARR_LED undeclared (first use in this function) error.

例如,当我尝试调用 SPECIFICPI​​N(x)时,其中x是for循环中的int迭代器,我收到一条错误消息,提示未声明类似"LEDx_PIN"的内容...

When I try to call SPECIFICPIN(x) where x is an int iterator in a for loop for example, I get an error saying something like 'LEDx_PIN' undeclared...

推荐答案

您需要使用术语.宏数组是不可能的.宏不是数据类型,而是在实际编译程序之前进行的文本替换.

You need to work on your terminology. An array of macros is not possible. Macros are no data type, but rather pure text replacement before your program is actually compiled.

我想"使用宏填充数组"是您想要做的.但是在编译时循环中这样做是不可能的-您似乎想通过 ioport_pin_t 宏尝试实现这一目标.宏不能扩展到比最初提供的更多的文本元素实例.没有诸如在编译时通过宏扩展进行循环以及对宏进行重复扩展之类的功能.

I guess " populate an array using macros " is what you want to do. But it is not possible to do that in a compile-time loop - What you seem to want to achieve with your ioport_pin_t macro attempt. Macros do not have the capability to expand to more instances of text elements than you have initially given. There is no such feature as looping at compile time through macro expansions and do repetitive expansion of macros.

您的 for 循环在运行时循环,而宏在编译时进行扩展.一旦意识到了预处理器完成了什么,编译器完成了什么,以及完成的程序在运行时完成了什么,您就会发现这是行不通的.

Your for loop loops at run-time, while the macro is being expanded at compile-time. Once you have made yourself aware what is done by the preprocessor what is done by the compiler, and what is done at run-time by the finished program, you will see that will not work.

类似

#define P(X) {(LED##X##_PIN)}

ioport_pin_t *commands[LED_COUNT] = {
  P(0), P(1), P(2),......}

#undefine P

将是您似乎想要的最接近的东西.请注意,预处理器的主要用途不是节省您的打字工作-您最好使用copy&粘贴到您的编辑器中,实现相同的操作并获得更清晰的代码.

Would be the closest thing possible to what you seem to want. Note the main use of the pre-processor is not to save you typing effort - You would be better off using copy & paste in your editor, achieve the same thing and have clearer code.

这篇关于c中的宏数组-是否可能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 18:57