I am new in Lex/Yacc programming. I have a question about how to call a function in Yacc file from another C file. Assume that I have following Lex/Yacc code:
calc.l
%{
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ { yylval=atoi(yytext); return NUMBER;}
[ \t];
\n return 0;
. return yytext[0];
%%
calc.y
%{
#include <stdio.h>
%}
%token NAME NUMBER
%%
statement: NAME '=' expression
| expression {printf("= %d\n",$1); printf("yylval= %d",yylval);}
;
expression: NUMBER '+' NUMBER {$$=$1+$3;}
| NUMBER '-' NUMBER {$$=$1-$3;}
| NUMBER 'x' NUMBER {$$=$1*$3;}
| NUMBER '/' NUMBER
{ if($3 == 0)
yyerror("Error, cannot divided by zero");
else
$$=$1/$3;
}
| NUMBER {$$=$1;}
;
%%
void parse()
{
while(1)
{
printf("Please enter numerical expression here: ");
yyparse();
}
}
And I created a main.c file so I could call the function void parse() in Yacc file like this:
main.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "y.tab.c"
#include "lex.yy.c"
int main(int argc,char* argv[])
{
parse();
}
The question is how I can call void parse() function in main.c and how to compile the main.c along with the Lex and Yacc file. I have tried with
- yacc -d calc.y
- lex calc.l
- gcc -o main main.c
But it didn't work.