Lex and Yacc Learn (vi) the Lex & Yacc (Simple calculator program) runs

Source: Internet
Author: User
Lexical analysis program CH3-01.L

%{
#include "ch3-01.tab.h"
extern int yylval;
%}

percent
(0-9]+	{yylval = Atoi (yytext); return number;}
[\ t]	;		/* Ignore white space */
\ n	return 0;	/* Logical EOF */
.	return yytext[0];
%%

CH3-01.Y Syntax Analysis program

%token name number
percent
statement:	name ' = ' Expression
	|	Expression		{printf ("=%d\n", $);}
	;

Expression:	expression ' + ' number	{$$ = $ + $;}
	|	Expression '-' number	{$$ = $-$;}
	|	Number			{$$ = $;}
	;
Percent of
int main ()
{
	yyparse ();
	return 0;
}

int Yyerror (char *s)
{
	printf ("%s/n", s);
	return 0;
}
compile Run command:

(1) First, compile the lex file, generate the Lex.yy.c file

Flex CH3-01.L


(2) Second, compile the Yacc file, generate Ch3-01.tab.h and CH3-01.TAB.C files

Bison-d CH3-01.Y


(3) Link the generated. c file and generate the appropriate executable file

Gcc-o ch3-01 CH3-01.TAB.C LEX.YY.C-LY-LFL


(4) Run the executable file to calculate a simple expression

./ch3-01.exe

99+11


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.