Compiler Design using Flex and Bison in Windows

Are you struggling while switching from Windows to Linux just for the compilation using lex and yacc?

Use flex and bison instead.

Steps to install Flex

  1. Download CodeBlocks-minGW setup from here and install it.
  2. Download Flex setup program from here and install it.
  3. After successfully installation go to CodeBlocks -> minGW -> bin and copy the address of rhe bin. Then go to environment variables->system variables->path->edit->new and paste the bin address here.
  4. Then go to C ->Program Files -> GnuWin32-> bin and again copy the address of the bin. Then go to environment variables->system variables->path->edit->new and paste it here.
  5. Make sure you keep the CodeBlocks path over the flex path as shown below:

Steps to install Bison

  1. Download DEV-CPP from here and install it.
  2. Download Bison setup program from here and change its path as shown below and install it.

3. After installation go to Dev-cpp -> MinGW64 -> bin and copy the address of the bin. Then add it to environment variables->system variables->path->edit->new.

4. Go to C -> GnuWin32 ->bin and copy the address the bin. Then add it to environment variables->user variables->path->edit->new.

adding bison file to user variables.

5. Make sure that your paths follow the following order:

I hope you guys have installed flex and bison successfully. To make sure run the following commands in command prompt.

Your files should contain following elements:

Lex file

  1. int yywrap(){return 1;}
  2. #include "file_name.tab.h" in definition section.

Yacc file

  1. #include "lex.yy.c" in definition section.
  2. void yyerror(char *s); in definiton section and define it outside any section. For instance:

void yyerror(char* s)

/* yacc error handler */

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

You can change the definition as per your need.

Commands to compile Lex program

Write your lex program in a text editor, save it with .l extension and run the following commands in command prompt:

  1. Enter into the folder where you have saved your lex file using cd command.
  2. flex file_name.l
  3. gcc lex.yy.c
  4. a.exe

For instance:

Commands to compile Yacc program

Write your lex and yacc program in a text editor, save it with .l and .y extensions respectively in same folder. Keep the filename for both the programs same. Then run the following commands in command prompt:

  1. Enter into the folder where you have saved your lex and yacc files using cd command.
  2. bison -d file_name.y
  3. flex file_name.l
  4. gcc file_name.tab.c -o file_name
  5. file_name

For instance:

Thank you guys! If you like it, dont forget to like and share.

Computer Science Student | BIT Mesra

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store