9

I am very new to Lex and Yacc. I have a Lex program. Example: wordcount.l

I am using windows and putty.

I am just trying to run this file..

  1. Does the wordcount.l file go on the C drive?

  2. Do I compile the Lex program and it generates a .c program and then what do I run?

I tried on the command-line: Lex wordcount.l

but I just get file not found...

wordcount.l

%{  
#include <stdlib.h>
#include <stdio.h>

int charCount=0;
int wordCount=0;
int lineCount=0;
%}
%%
\n      {charCount++; lineCount++;}   
[^ \t\n]+   {wordCount++; charCount+=yyleng;}
.       {charCount++;}

%%
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;
}

yylex();
printf("%d   %d   %d\n", charCount, wordCount, lineCount);
}

In putty how do I compile and run this program?

Farshid Shekari
  • 2,391
  • 4
  • 27
  • 47

2 Answers2

23

You first have to go to the directory which the file wordcount.l is in using cd. Then using lex wordcount.l will make the file lex.yy.c. To the run the program you need compile it with a c compiler such as gcc. With gcc you can compile it using gcc -lfl lex.yy.c. This will create a.out which can be run using ./a.out

Bilal Syed Hussain
  • 8,664
  • 11
  • 38
  • 44
  • I tried cd c:\ then hit enter then typed in lex wordcount.l and i still get an error: no such file or directory –  Jan 14 '12 at 03:35
  • @icelated Are you using putty to connect to a remote host(sever)? If so you need to copy the file to that host first. – Bilal Syed Hussain Jan 14 '12 at 03:43
  • I am using putty. What do you mean copy the file to the host? you mean copy the file to the server at school? Can i use SSH instead? –  Jan 14 '12 at 03:55
  • 2
    I believe the pure Lex uses `-ll` and Flex uses `-lfl`. Also, for reliability, you should list the library after the object or source files, so: `gcc lex.yy.c -ll` should be correct. Of course, the Windows prompt begs the question of 'Which version of Lex is in use?', since the original Lex was not ported there. It might be Flex after all, or maybe MKS Lex (& Yacc), or ... something else. – Jonathan Leffler Jan 14 '12 at 04:06
  • 1
    I have the same problem when i write lex wordcount.l i get 'lex' is not recognized as an internal or external command Do i need to install something fist and if I do what is it ? – Aya Abdelsalam Apr 12 '13 at 18:08
5
lex file.l
gcc lex.yy.c -ly -ll
./a.out

These also works. I am using this in Ubuntu 14.04.

alhelal
  • 916
  • 11
  • 27