C编程错误:未定义结构的符号(Keil错误L6218E)

C编程错误:未定义结构的符号(Keil错误L6218E),c,arm,keil,C,Arm,Keil,我正在使用Keil MDK ARM开发一个项目。但是,当我试图构建代码时,软件工具抛出错误:L6218E:Undefined symbol Bit(来自main.o)。 其中Bit是我用来存储布尔值的结构。例如: 在variable.h文件中 struct { unsigned bPowerONStatus : 1; unsigned bTimerONStatus : 1; } extern Bit; #include variable.h void ReadTimerSta

我正在使用Keil MDK ARM开发一个项目。但是,当我试图构建代码时,软件工具抛出错误:L6218E:Undefined symbol Bit(来自main.o)。 其中Bit是我用来存储布尔值的结构。例如:

在variable.h文件中

struct
{
    unsigned bPowerONStatus : 1;
    unsigned bTimerONStatus : 1;
} extern Bit;
#include variable.h

void ReadTimerStatus(void)
{
    if(Bit.bTimerONStatus)
    {
        Bit.bPowerONStatus = 1;
    }
    else
    {
        Bit.bPowerONStatus = 0;
    }
}

在main.c文件中:

#include variable.h

int main()
{
    while(1)
    {
        ReadTimerStatus();
        if(Bit.bPowerONStatus)
        {
            // System is ON
        }
        else
        {
            // System if OFF
        }
    }
}
struct StatusBits
{
    unsigned bPowerONStatus : 1;
    unsigned bTimerONStatus : 1;
};

extern struct StatusBits Bits;
#include "variable.h"

struct StatusBits Bits;
在PowerChecker.c文件中

struct
{
    unsigned bPowerONStatus : 1;
    unsigned bTimerONStatus : 1;
} extern Bit;
#include variable.h

void ReadTimerStatus(void)
{
    if(Bit.bTimerONStatus)
    {
        Bit.bPowerONStatus = 1;
    }
    else
    {
        Bit.bPowerONStatus = 0;
    }
}


我做错了什么?定义将在多个源文件中使用的结构的正确方法是什么?

使用关键字
extern
在文件范围内声明变量,但不使用初始值设定项声明变量具有外部链接,但不定义变量。在程序的其他地方需要有变量的定义

对于
变量,它是用一个匿名
结构
类型声明的,该类型没有类型别名,因此在定义变量时无法使用相同的类型。为了解决这个问题,您需要使用标记定义
struct
类型,或者在
typedef
声明中定义
struct
类型,或者您可以同时执行这两项操作

更传统的做法是将存储类说明符(如
extern
)放在声明的前面

在变量中。h:

#include variable.h

int main()
{
    while(1)
    {
        ReadTimerStatus();
        if(Bit.bPowerONStatus)
        {
            // System is ON
        }
        else
        {
            // System if OFF
        }
    }
}
struct StatusBits
{
    unsigned bPowerONStatus : 1;
    unsigned bTimerONStatus : 1;
};

extern struct StatusBits Bits;
#include "variable.h"

struct StatusBits Bits;
仅在一个C文件中,例如main.C或variable.C:

#include variable.h

int main()
{
    while(1)
    {
        ReadTimerStatus();
        if(Bit.bPowerONStatus)
        {
            // System is ON
        }
        else
        {
            // System if OFF
        }
    }
}
struct StatusBits
{
    unsigned bPowerONStatus : 1;
    unsigned bTimerONStatus : 1;
};

extern struct StatusBits Bits;
#include "variable.h"

struct StatusBits Bits;

请注意,
struct StatusBits具有外部链接且没有初始值设定项,但尚未声明
extern
,因此它是
变量的暂定定义。除非使用初始值设定项被同一变量的定义覆盖,否则它的行为将如同已使用
{0}

初始化一样。这是否回答了您的问题?首先,您应该对include语句使用引号--
#include“variable.h”
(假设它与main.c和PowerChecker.c位于同一文件夹中)。我不确定struct{…}extern Bit
应该做什么。您可能应该做的是在标头中创建一个typedef结构,然后在其他地方创建该结构的实例。还请注意,不建议使用位字段,因为它们是特定于编译器的。