GNU Bison is a widely used parser generator that converts grammar definitions into C programs. It is commonly used in compiler construction and language processing tasks. This tutorial explains how to install the GNU Bison on Ubuntu 26.04.
Prepare environment
Before starting, ensure that the GCC compiler is installed.
sudo apt install -y gcc
Install GNU Bison
Make sure that the package lists are up-to-date:
sudo apt update
Install the GNU Bison using the following command:
sudo apt install -y bison
Verify that the GNU Bison is available by checking version:
bison --version
Testing GNU Bison
A simple grammar file helps demonstrate parsing behavior. Create a file named main.y:
nano main.y
Insert the following content:
%{
#include <stdio.h>
#include <stdlib.h>
int yylex(void);
void yyerror(const char *s);
%}
%%
input:
'a' { printf("Found a\n"); }
;
%%
int yylex(void) {
int c;
while ((c = getchar()) == ' ' || c == '\n' || c == '\t');
return c == EOF ? 0 : c;
}
void yyerror(const char *s) {
fprintf(stderr, "Error: %s\n", s);
}
int main(void) {
return yyparse();
}
This grammar defines a minimal rule that recognizes a single character input.
GNU Bison processes the grammar file and produces C source and header files:
bison -d main.y
Generated files include: main.tab.c and main.tab.h. The generated C file can be compiled using the command:
gcc main.tab.c -o test
The compiled program reads input and reacts based on the grammar rules. Valid input:
echo a | ./test
Output:
Found a
Invalid input:
echo b | ./test
Output:
Error: syntax error
Uninstall GNU Bison
If GNU Bison is no longer needed, uninstall it by running the following command:
sudo apt purge --autoremove -y bison
Leave a Comment
Cancel reply