Flex/Bison编写Hello World解析器编译警告如何消除?
警告含义
implicit declaration of function 'yylex':Bison生成的yyparse依赖Flex生成的yylex函数,但你没有在语法文件的代码块中提前声明yylex,编译器找不到函数定义触发隐式声明警告。implicit declaration of function 'yyerror':yyparse执行报错时需要调用yyerror,但你没有提前声明该函数,且定义放在了main之后,触发隐式声明警告。return type defaults to 'int':你定义的yyerror没有指定返回值类型,旧版C标准会默认返回int,现代编译器会对这种写法发出警告。assignment to 'YYSTYPE' {aka 'int'} from 'char *':Bison默认的语义值类型YYSTYPE是int,但你在词法文件中直接把字符串指针yytext赋值给了yylval,类型不匹配触发类型转换警告。
修复方案
- 修改语法文件
helloworld.y,补充函数声明、指定语义值类型、补全yyerror返回值:
%{ #include <stdio.h> // 提前声明依赖的函数 int yylex(void); void yyerror(char *s); // 定义语义值为字符串指针类型,匹配后续字符串传递需求 #define YYSTYPE char* %} %token DATA %token EOL %% start: /* 空规则 */ | data EOL { printf("<Document>%s</Document>\n> ", $1); } ; data: DATA { $$ = $1; } ; %% int main() { printf("> "); yyparse(); return 0; } // 补全void返回值类型 void yyerror(char *s) { fprintf(stderr, "error: %s\n", s); }
- 修改词法文件
helloworld.l,复制字符串内容避免缓冲区复用导致数据异常:
%{ #include "helloworld.tab.h" #include <string.h> %} %% .+ { yylval = strdup(yytext); return(DATA); } \n { return(EOL); } %% int yywrap(){ return 1;}
修改后重新执行make编译即可消除所有警告,运行后输入Hello, World就能得到预期的XML输出。
内容的提问来源于stack exchange,提问作者Roger Costello
相关产品推荐
相关产品推荐

