Call a function in a Yacc file from another c file

2019-07-22 08:42发布

问题:

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

  1. yacc -d calc.y
  2. lex calc.l
  3. gcc -o main main.c

But it didn't work.

回答1:

Try compiling all of the files together as below:

gcc lex.yy.c y.tab.c main.c -o main

And try running it as follows:

./main



标签: c yacc lex