Skip to content
Victor Rodriguez edited this page Apr 27, 2026 · 1 revision

📘 Lex (Flex) & Yacc (Bison) Setup and Basic Tutorial

1. Overview

This guide explains how to install and validate Lex/Yacc tooling on:

  • Linux
  • WSL (Windows Subsystem for Linux)
  • macOS

Modern equivalents:

  • Flex → lexical analyzer generator
  • Bison → Yacc-compatible parser generator

2. Installation

2.1 Ubuntu / WSL

sudo apt update
sudo apt install -y flex bison gcc make

2.2 Fedora / RHEL

sudo dnf install -y flex bison gcc make

2.3 macOS (Homebrew)

brew install flex bison

Add to PATH if needed:

# Apple Silicon
echo 'export PATH="/opt/homebrew/opt/bison/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/opt/homebrew/opt/flex/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

3. Basic Verification

flex --version
bison --version
gcc --version

This only confirms installation—not correctness of the toolchain.


✅ 4. Environment Validation (Critical Step)

This step ensures your full pipeline actually works:

  • Flex → C code generation
  • GCC → compilation
  • Runtime → execution

4.1 Create Minimal Test

cat > test.l <<'EOF'
%{
#include <stdio.h>
%}

%%

hello { printf("OK: FLEX WORKS\n"); }
.|\n { }

%%

int main(void) {
yylex();
return 0;
}

int yywrap(void) { return 1; }
EOF

4.2 Generate + Compile + Run

flex test.l
gcc lex.yy.c -o test
echo "hello" | ./test

4.3 Expected Output

OK: FLEX WORKS

4.4 Failure Diagnosis

Symptom | Likely Cause | Fix -- | -- | -- flex: command not found | Not installed / PATH issue | Reinstall or fix PATH gcc: command not found | Compiler missing | Install build-essential undefined reference to yywrap | Missing symbol | Add yywrap() or link -lfl No output | Rule not matching | Check regex or input

7. Next Steps

  • Integrate Flex with Bison
  • Build a parser (calculator example)
  • Generate AST and semantic checks

8. Summary

The validation step (Section 4) is the most important addition:

✔ Confirms toolchain integrity
✔ Eliminates environment issues early
✔ Guarantees Flex → GCC → runtime pipeline works