Bison中%union无法识别bool类型及结构体指针的问题
问题2:%union中结构体指针报错的解决
核心原因
Bison处理%union时,需要提前知晓结构体的类型声明。若structName仅在semantics.h中定义,但头文件未包含前向声明,或%{ ... %}块中include顺序错误,编译器会认为structName是隐式声明的未知类型,触发报错。
可行解决方案
- 添加结构体前向声明:在
%{ ... %}块开头,include头文件之前添加前向声明:struct structName; #include "semantics.h" - 确保头文件包含完整声明:检查
semantics.h,确保里面已经包含struct structName;的前向声明或完整结构体定义。
修改后的示例代码
%{ #include <stdbool.h> #include "semantics.h" #include "IOMngr.h" #include <string.h> extern int yylex(); extern char *yytext; extern int yyerror(char *s); extern SymTab *table; extern SymEntry *entry; %} %union{ _Bool boolean; // 改用C99原生布尔类型,避免宏依赖 char * string; } %type <string> Id %type <boolean> Expr %type <boolean> Term %type <boolean> Factor %token Ident %token TRUE %token FALSE %token OR %token AND %% Prog : StmtSeq {printSymTab();}; StmtSeq : Stmt StmtSeq { }; StmtSeq : { }; Stmt : Id '=' Expr ';' {storeVar($1, $3);}; Expr : Expr OR Term {$$ = doOR($1, $3);}; Expr : Term {$$ = $1;}; Term : Term AND Factor {$$ = doAND($1, $3);}; Term : Factor {$$ = $1;}; Factor : '!' Factor {$$ = doNOT($2);}; Factor : '(' Expr ')' {$$ = $2;}; Factor : Id {$$ = getVal($1);}; Factor : TRUE {$$ = true;}; Factor : FALSE {$$ = false;}; Id : Ident {$$ = strdup(yytext);}; %% int yyerror(char *s) { WriteIndicator(getCurrentColumnNum()); WriteMessage("Illegal Character in YACC"); return 1; }
内容的提问来源于stack exchange,提问作者justacat
相关产品推荐
相关产品推荐

