如何編譯 Lex 和 Yacc?
假設有一 檔名為 ch3-01.l Lex 檔案,內容如下:
%{

#include "y.tab.h"

extern int yylval;

%}

 

%%

[0-9]+      { yylval = atoi(yytext); return NUMBER; }

[ \t]   ;               /* ignore white space */

\n     return 0;  /* logical EOF */

.       return yytext[0];

%%

另有一檔名為 ch3-01.y Yacc 檔案,內容如下:
%{

        #include <stdio.h>

%}

 

%token NAME NUMBER

%%

statement:      NAME '=' expression

        |       expression             { printf("= %d\n", $1); }

        ; 

expression:    expression '+' NUMBER      { $$ = $1 + $3; }

        |       expression '-' NUMBER       { $$ = $1 - $3; }

        |       NUMBER                       { $$ = $1; }

        ;
 

%%

main()

{

                yyparse();      

}

 yyerror(s)

char *s;

{

        fprintf(stderr, "%s\n", s);

}

編譯方法如下:

[shenjh@db /shenjh]# yacc -d ch3-01.y
[shenjh@db /shenjh]# lex ch3-01.l
[shenjh@db /shenjh]# cc -o ch3-01 y.tab.c lex.yy.c -lfl

第一行 "yacc -d ch3-01.y" 會產生 y.tab.c 和 y.tab.h;
第二行 "lex ch3-01.l" 會產生 lex.yy.c;
第三行 "cc -o ch3-01 y.tab.c lex.yy.c -lfl" 會編譯和連結 c 檔案。

程式執行結果:
[shenjh@db /shenjh]# ./ch3-01
23 + 50
= 73



 

如何讓 yacc 的輸入從檔案讀入?

%%

extern FILE *yyin;

main(argc, argv)

int argc;

char **argv;

{

        if (argc > 1) {

                FILE *file;

                file = fopen(argv[1], "r");

                if (!file) {

                        fprintf(stderr, "could not open %s\n", argv[1]);

                        exit(1);

                }

       

                yyin = file;

                do

                        {

                                yyparse();

                        }

                while (!feof(yyin));

        }

}