从另一个C文件调用Yacc文件中的函数 [英] Call a function in a Yacc file from another c file
问题描述
我是Lex/Yacc编程的新手.我有一个关于如何从另一个C文件调用Yacc文件中的函数的问题.假设我有以下Lex/Yacc代码:
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:
计算量
%{
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ { yylval=atoi(yytext); return NUMBER;}
[ \t];
\n return 0;
. return yytext[0];
%%
计算
%{
#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();
}
}
然后我创建了一个main.c文件,因此可以像这样在Yacc文件中调用函数void parse():
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();
}
问题是如何在main.c中调用void parse()函数,以及如何将Lex和Yacc文件与main.c一起编译.我尝试过
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
但这没用.
推荐答案
尝试如下一起编译所有文件:
Try compiling all of the files together as below:
gcc lex.yy.c y.tab.c main.c -o main
gcc lex.yy.c y.tab.c main.c -o main
并尝试按以下方式运行它:
And try running it as follows:
./main
这篇关于从另一个C文件调用Yacc文件中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!