Compiler Design

Table of Contents

Currently I am using Fedora, so things can be different for Debian based Distros. But I will try to add resources for them too.

Fedora:

$ dnf install flex bison
$ dnf install flex-devel bison-devel

Ubuntu/Debian:

sudo apt-get update
sudo apt-get install flex
sudo apt-get install bison

Creating Lex programs:

Create a file named counter.l:

Add this program to it.

%{
    #include<stdio.h> 
    int n, m, t, c;
%}


%%
\n n++;
\t t++;
[ ] m++;
. c++;
%%

int main(){
    yylex();
    printf("Total number of lines is %d, \n Number of tabs is %d, \n Number of spaces is %d, \n Number of characters is %d", n, t, m, c);
}

int yywrap(){
return 1;
}

Run this program:

$ lex counter.l

Any error will be shown in terminal output.

A file named lex.yy.c will be generated.

$ gcc lex.yy.c

Then gcc will give the output in a.out file.

$ ./a.out

Enter some characters , lines, tabs, spaces. Then [CTRL + D] You’ll get an output.

Resources:

Tags :