Arduino:无法通过联合结构作为指针 ac 我可以使用 gcc 编译器 [英] Arduino: cannot pass union struct as pointer ac I can with gcc compiler

查看:32
本文介绍了Arduino:无法通过联合结构作为指针 ac 我可以使用 gcc 编译器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Arduino 中使用结构,但无法通过函数调用传递结构指针.添加主函数并使用 gcc 为我的计算机编译时一切正常,但使用 Arduino IDE 时出现错误.

I'm trying to use structs with Arduino but cannot pass a struct pointer with a function call. Everything works fine when adding a main function and compiling for my computer with gcc but with the Arduino IDE I get errors.

我尝试的代码是:

typedef union
{
    struct
    {
        unsigned unit   :2;
        unsigned channel:2;
        unsigned status :1;
        unsigned group  :1;
        unsigned remote :26;
    };
    unsigned long data;
} Signal;

Signal signal;

void testPassingStruct(Signal *variable)
{
    variable->status = 1;
}

void setup()
{
    signal.status = 1;
    testPassingStruct(&signal);
}

void loop()
{
}

错误是:

structtest:2: error: variable or field ‘testPassingStruct’ declared void
structtest:2: error: ‘Signal’ was not declared in this scope
structtest:2: error: ‘variable’ was not declared in this scope

推荐答案

您有几个未命名项目.这发生在 typedefs 上.你可以试试,

You have several unnamed items. This happens with typedefs. You could try,

union sig_union
{
    struct
    {
        unsigned unit   :2;
        unsigned channel:2;
        unsigned status :1;
        unsigned group  :1;
        unsigned remote :26;
    } d;                       /* Note the name here. */
    unsigned long data;
} signal;
typedef union sig_union Signal;

然后在您需要的代码中,

Then in your code you need,

void testPassingStruct(Signal *variable)
{
    variable->d.status = 1;
}

您还可以对掩码和位域使用定义.通常它可以控制哪个位更清晰,并且编译器将在两种情况下生成类似的代码.例如,

You can also use defines for masks and bit fields. Often it makes control of what bit is where clearer and the compiler will generate similar code in both cases. For instance,

#define SIG_UNIT(d)    (d&0x3)
#define SIG_CHANNEL(d) (d&0xc>>2)
#define SIG_STATUS(d)  (d&0x10)
/* etc. */

特别是对于位很重要的系统编程,这更好,因为我不相信C"位字段指定它们的放置方式.最重要的是,我相信它会编译.

Especially with system programming where the bits matter, this is better as I don't believe that the 'C' bit fields specify how they are placed. Most of all, I am sure it will compile.

这篇关于Arduino:无法通过联合结构作为指针 ac 我可以使用 gcc 编译器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆