By default, Flex and Bison generate old-school code with global variables. Trawling the manuals to find the options that generate re-entrant code is tedious, so I’m recording a small example that works on my system (which has Bison 2.7.12 and Flex 2.5.35).
With these options, yylval is now a pointer. When converting existing Flex source, we mostly replace with yylval with *yylval.
%option outfile="flex.c" header-file="flex.h"
val.h: semantic values
Rather than use the %union Bison declaration or similar, I prefer to define the type that holds the semantic values in a C source file. In general, I like to minimize the amount of C in the Bison and Flex source.
Calling the parser
Because the parser is no longer global, we must initialize and pass a yyscan_t variable to Bison and Flex.
See https://github.com/blynn/symple/, which reads an expression and pretty-prints it:
$ ./main 'sin(x)*cos(y) + e^x'