从lex和yacc语法生成编译器

Cha*_*ars 7 c yacc lex

我正在尝试生成一个编译器,所以我可以在之后传递一个.c文件.

我从http://www.quut.com/c/ANSI-C-grammar-y.html下载了YACC和LEX语法,并将它们命名为clexyacc.l和clexyacc.y

在终端上生成它时我做了:

yacc -d clexyacc.y
lex clexyacc.l
Run Code Online (Sandbox Code Playgroud)

一切都很好.当我继续到最后一部分时,我得到了一些错误.

最后一部分是:cc lex.yy.c y.tab.c -oclexyacc.exe

但我得到这些错误:

y.tab.c:2261:16: warning: implicit declaration of function 'yylex' is invalid in
      C99 [-Wimplicit-function-declaration]
      yychar = YYLEX;
               ^
y.tab.c:1617:16: note: expanded from macro 'YYLEX'
# define YYLEX yylex ()
               ^
y.tab.c:2379:7: warning: implicit declaration of function 'yyerror' is invalid
      in C99 [-Wimplicit-function-declaration]
      yyerror (YY_("syntax error"));
      ^
clexyacc.y:530:6: error: conflicting types for 'yyerror'
void yyerror(const char *s)
     ^
y.tab.c:2379:7: note: previous implicit declaration is here
      yyerror (YY_("syntax error"));
      ^
2 warnings and 1 error generated.
Run Code Online (Sandbox Code Playgroud)

har*_*mic 12

您使用的yacc版本产生的C代码对C99无效.

它生成的代码在调用它们之前不包括函数yylex或yyerror的声明.这是在发出警告.在yyerror的情况下,它还导致隐式声明与后面的实际定义不匹配.

你可以通过在.y文件的顶部包含以下内容来解决它:

%{
int yylex();
void yyerror(const char *s);
%}
Run Code Online (Sandbox Code Playgroud)

或者,您可以切换到更现代的yacc编译器.

另请参见:简单的yacc语法给出错误