Call a function in a Yacc file from another c file

自古美人都是妖i 提交于 2019-12-11 04:36:40

问题


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



来源:https://stackoverflow.com/questions/40999748/call-a-function-in-a-yacc-file-from-another-c-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!