lex yacc簡單實例

//文件Name.y

%{

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedef char* string;

#define YYSTYPE string

%}

%token NAME EQ AGE

%%

file : record file

| record

;

record : NAME EQ AGE {

printf("%s is %s years old!!!\n",$1,$3);}

;

%%

 

int main()

{

yyparse();

return 0;

}

int yyerror(char *msg)

{

         printf("Error encountered:%s \n",msg);

}

 

//Name.l文件

%{

#include "y.tab.h"

#include <stdio.h>

#include <string.h>

extern char* yylval;

%}

char [A-Za-z]

num [0-9]

eq [=]

name {char}+

age {num}+

%%

{name} {yylval=strdup(yytext);

              return NAME;}

{eq} {return EQ;}

{age} {yylval=strdup(yytext);

           return AGE;}

%%

 

int yywrap()

{

          return 1;

}

 

//text.txt

test = 123

 

編譯鏈接:

$yacc -d Name.y

$lex Name.l

$gcc y.tab.c lex.yy.c

$./a.out < text.txt

輸出:test is 123 years old!!!

 

發佈了33 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章