我正在使用 Visual Studio 使用 C 语言开发小型项目。 为了避免多次包含,我使用了包含守卫。
我遇到了很多错误,包括这个:
文件:collections.h
错误:C2061
描述:语法错误:标识符“终端”
synt_analysis.c
#include <string.h>
#include "headers\synt_analysis.h"
语法分析.h
#ifndef SYNT_ANALYSIS_H
#define SYNT_ANALYSIS_H
#include "collections.h"
typedef enum {
...
}TType;
typedef enum {
...
}NTType;
typedef struct {
TType type;
...
}Terminal;
void push_terminal(Terminal terminal, cStack *stack);
#endif
集合.h
#ifndef COLLECTIONS_H
#define COLLECTIONS_H
#include "synt_analysis.h"
typedef union {
int error;
Terminal terminal;
NTType nttype;
}cItemData;
typedef struct {
char *type;
cItemData content;
}cItem;
typedef struct {
unsigned cap;
unsigned used;
cItem *items;
}cStack;
#endif
collections提供cStack
,可以存放synt_analysis定义的Terminal
。
synt_analysis 在函数 push_terminal
中使用 cStack
- 将 Terminal
推送到堆栈上。此函数的存在是为了减少所需的代码量(它创建新的 Terminal
并将其推送到 cStack
上)。
最佳答案
因为这个问题不能简单地通过前向声明来解决(编译器需要知道不完整结构类型的大小——它被用作 union 的一个选项),解决方案是创建另一个头文件,这将打破循环依赖。
新建文件synt_structures.h
#ifndef SYNT_STRUCTURES_H
#define SYNT_STRUCTURES_H
#include "lex_analysis.h"
typedef enum {
...
}NTType;
typedef enum {
...
}TType;
typedef struct {
TType type;
...
}Terminal;
#endif
synt_analysis.h 包括:
#include "collections.h"
#include "synt_structures.h"
collections.h 包括:
#include "synt_structures.h"
这打破了循环。
关于C VS 循环依赖? ERROR C2061 - 标识符语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40760550/