简体   繁体   English

尝试从.c文件中的标头使用结构时,为什么会出现类型错误?

[英]Why am I getting a type error when trying to use a struct from a header in my .c file?

I really don't understand what is happening here. 我真的不明白这里发生了什么。 I'm trying to access members of a struct in a .c file, but it's giving an 'error-type' when I try to access the struct variable. 我正在尝试访问.c文件中的结构成员,但是当我尝试访问struct变量时,它给出了“错误类型”。 Anybody have any idea what's going on here? 有人知道这是怎么回事吗?

CPU.h Header file: CPU.h头文件:

#ifndef _CPU_H
#define _CPU_H

#include <stdint.h>

typedef struct cpu_registers
{
    union
    {
        struct
        {
            uint8_t f;
            uint8_t a;
        };
        uint16_t af;
    };
    union
    {
        struct
        {
            uint8_t c;
            uint8_t b;
        };
        uint16_t bc;
    };
} cpu_registers;

#endif /* _CPU_H */

CPU.c file: CPU.c文件:

#include "CPU.h"

cpu_registers regs;
regs.af = 0xFFFF;

Here are the errors upon compilation with clang: 这是使用clang编译时的错误:

CPU.c:4:1: error: unknown type name 'regs'
regs.af = 0xFFFF;
^
CPU.c:4:5: error: expected identifier or '('
regs.af = 0xFFFF;
    ^
2 errors generated.

You can declare and initialize global variables outside of functions, but you cannot do anything else with them. 您可以在函数外部声明和初始化全局变量,但不能对它们执行任何其他操作。

So, you could do this: 因此,您可以这样做:

cpu_registers regs = { .af = 0xFFFF };

However, do note that this will not work: 但是,请注意,这将不起作用:

int val = 0xFFFF;
cpu_registers regs = { .af = val };

And - maybe a bit surprisingly - not this either: 而且-也许有点令人惊讶-也不是:

const int val = 0xFFFF;
cpu_registers regs = { .af = val };

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

相关问题 为什么在我的 UDP 服务器上尝试使用 sendto() 时会收到错误地址错误? - Why am I getting a bad address error when trying to use sendto() on my UDP server? 为什么尝试在c中打印矩阵时出现此错误? - Why am I getting this error when trying to print a matrix in c? 为什么在尝试填充结构时出现分段错误(核心已转储)或总线错误(核心已转储)? - Why am I getting Segmentation fault (core dumped) or bus error (core dumped) when trying to populate a struct? 为什么在尝试编译 C 代码时会收到这些错误? - Why am I getting these errors when I am trying to compile my C code? 为什么在 Atmel Studio 7 中使用 struct 时出现错误? - Why am I getting an error when using struct in Atmel Studio 7? 声明结构时,我在 c 中遇到分段错误 - I am getting segmentation error in c when declaring a struct 尝试“捕获” char设备驱动程序时,为什么会收到错误消息? - Why am I getting an error message when trying to “cat” my char device driver? 尝试将指针与struct结合使用时出现错误 - Getting error when trying to use pointer with struct 为什么在尝试写入文件时会出现额外字符? - Why am I getting extra character when trying to write to file? 当我尝试在C中读取文件时,为什么fscanf随机更改字符串中的字符? - Why does fscanf randomly change characters in my strings when I am trying to read a file in C?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM