lexical analysis - Difference "Flex and Bison" code in windows and linux -
i working through sample code o'reilly press book entitled "flex , bison". using gnu c compiler windows flex , bison binary install windows launched using gcc rather linux cc command. problem code if copied directly book not compile , have had hack bit work.
example book
example 1-1. word count fb1-1.l /* unix wc */ %{ int chars = 0; int words = 0; int lines = 0; %} %% [a-za-z]+ { words++; chars += strlen(yytext); } \n { chars++; lines++; } . { chars++; } %% main(int argc, char **argv) { yylex(); printf("%8d%8d%8d\n", lines, words, chars); }
i compiled code in flowing way using windows command line: flex file.l gcc lex.yy.c -o a.exe
it crashed stating yywrap() not found. added , worked did not complete printf in main function hung waiting more input!
here solution works feels hack , not in full understanding of process.
/* unix wc */ %{ *#include <string.h>* int chars = 0; int words = 0; int lines = 0; %} %% [a-za-z]+ { words++; chars += strlen(yytext); } \n { chars++; lines++; } *"." { return ;}* . { chars++; } %% *int yywrap(void) { return 1; }* int main(void) { yylex(); printf("num lines %8d, num words %8d, num chars %8d\n", lines, words, chars); return 0; }
i had add new rule return out of yylex() not in book, add yywrap()- not knowing why , add string.h not present!. main question there significant differences between flex windows , unix , possible run original code gcc compiler , gnu flex without said hacks?
i not understand have achieved this:
#include <string.h> "." { return; }
but know sure if running flex without specified input file have mark end of input. otherwise flex wait input. suggest:
%{ #include <stdio.h> int chars = 0; int words = 0; int lines = 0; %} word [a-za-z]+ %% {word} { words++; chars += strlen(yytext); } \n { lines++; /* chars++; why this? there no columns here - it's new line */ } \s { /* count spaces */ chars++; } \t { /* count tabs */ chars += 4 /* or 8 */; } . { printf("error (unknown symbol):\t%c\n", yytext[0]); chars++; } %% int main() { /* iterate until end of input , if errors - continue */ while(yylex()){ } printf("lines:\t%8d\nwords:\t%8d\nchars:\t%8d\n", lines, words, chars); return 0; }
build with:
flex input.l
output lex.yy.c build:
gcc -o scanner.exe lex.yy.c -lfl
create txt file input. run following:
scanner.exe <in.txt>out.txt
less sign means redirect input file in.txt while greater sign means redirect output out.txt cause file has eof @ end of file flex stop.
Comments
Post a Comment