我正在尝试解决一个头中的函数需要一个结构作为参数的问题,该参数包含与函数相同的头中的结构。代码如下:
Nintendo.h
/**
* Nintendo.h - Nintendo Entertainment System
*
* This header file is the struct that cotains every component of our
* Ninetendo Entertainment System. This is the core file, so to speak,
* that brings together components such as the CPU, PPU, and APU, along
* with some other smaller components.
*/
#ifndef _NINTENDO_H
#define _NINTENDO_H
#include "Registers.h"
typedef struct Nintendo
{
Registers reg;
} Nintendo;
#endif /* _NINTENDO_H */Registers.h
#ifndef _REGISTERS_H
#define _REGISTERS_H
#include "Constants.h"
#include "Nintendo.h"
typedef struct Registers
{
/* Special Purpose Registers */
Uint16 pc; /* Program Counter */
Uint8 sp; /* Stack Pointer */
/* Bit 7 - Negative Flag N
Bit 6 - Overflow Flag V
Bit 5 - Unused
Bit 4 - Break Command B
Bit 3 - Decimal Mode D
Bit 2 - Interrupt Disable I
Bit 1 - Zero Flag Z
Bit 0 - Carry Flag C
*/
Uint8 p; /* Processor Status */
/* General Purpose Registers */
Uint8 a; /* Accumulator */
Uint8 x;
Uint8 y;
} Registers;
void InitializeRegisters(Nintendo *nes);
#endif /* _REGISTERS_H */正如您所看到的,'InitializeRegisters‘函数接受任天堂结构作为参数,但该任天堂结构在其定义中包含了寄存器结构。这导致了循环依赖问题。
我知道我可以通过让参数接受寄存器*并只传递&Nintendo.reg来解决这个问题,但我不想这样做。
以下是错误输出:
In file included from source/Nintendo.h:13:
source/Registers.h:31:26: error: unknown type name 'Nintendo'
void InitializeRegisters(Nintendo *nes);
^
1 error generated.
In file included from source/Registers.h:5:
source/Nintendo.h:17:5: error: unknown type name 'Registers'
Registers reg;
^
1 error generated.
/bin/ld: /bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.0/../../../../lib64/Scrt1.o: in function `_start':
(.text+0x24): undefined reference to `main'
clang-6.0: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [Makefile:2: test] Error 1发布于 2018-09-06 07:59:37
最简单的答案是添加下面这行:
typedef struct Nintendo Nintendo;在registers.h的顶部附近(对头文件使用大小写混合是一个非常糟糕的主意)。C语言的一个特点是,如果类型定义的语句都是一致的,那么它们就可以被重复,并且可以作为一个“向前声明”,这正是您所需要的。
如果你想反常,你可以把它放在#ifndef行上面的nintend.h中,但是如果你喜欢的话,还有其他方法可以让你快乐起来。
https://stackoverflow.com/questions/52194701
复制相似问题