Reputation: 25
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. Anybody have any idea what's going on here?
#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 */
#include "CPU.h"
cpu_registers regs;
regs.af = 0xFFFF;
Here are the errors upon compilation with 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.
Upvotes: 0
Views: 272
Reputation: 31296
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 };
Upvotes: 6