Generating a compiler from lex and yacc grammar

ChasingCars picture ChasingCars · May 18, 2014 · Viewed 12.8k times · Source

I'm trying to generate a compiler so I can pass him a .c file after.

I've downloaded both YACC and LEX grammars from http://www.quut.com/c/ANSI-C-grammar-y.html and named them clexyacc.l and clexyacc.y

When generating it on terminal I did :

yacc -d clexyacc.y
lex clexyacc.l

All went fine. When I move on to the last part I get a few errors.

The last part is : cc lex.yy.c y.tab.c -oclexyacc.exe

But I get these errors :

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.

Answer

harmic picture harmic · May 18, 2014

The version of yacc you are using is producing C code which is invalid for C99.

The code it produces does not include declarations for the functions yylex or yyerror prior to calling them. This is producing the warnings. In the case of yyerror, it is also resulting in an implicit declaration which does not match the later actual definition.

You can get around it by including the following at the top of the .y file:

%{
int yylex();
void yyerror(const char *s);
%}

Or, you can switch to a more modern yacc compiler.

See also this: Simple yacc grammars give an error