You can replace yylex and pass your own arguments, is there any simple way to do this with yywrap?
If you are building an ordinary non-reentrant scanner, you can define yywrap
as a macro. That macro could expand to a call to an arbitrary function with arbitrary arguments. (In this scenario, most of the things you could plausibly pass to your wrap function are globals, but it could be useful to pass through arguments passed to yylex
.)
However, you need to put the macro definition in the inserted code at the top of yylex, because of the forward declaration of of yywrap
in the generated code.
So your file might include:
%{
#define YY_DECL int yylex(Frobber* data)
/* Forward declaration of mywrap
int mywrap(Frobber* data);
%}
%option ...
%%
/* Indented lines before the first rule are inserted at the top of yylex
#define yywrap() mywrap(data)
Defining yywrap
as a macro is not explicitly permitted by the flex documentation, nor by Posix. So it should probably at least be accompanied with a comment, in case some later version does something which somehow prevents it from working. Putting the definition at the top of yylex
is a bit of a hack, and may not be necessary with old lex versions.
There is a cleaner solution, if you are prepared to build a re-entrant scanner. In a reentrant scanner, yywrap
will be automatically called with the same scanner argument that yylex
will be called with. The scanner context object scanner_t scanner
can be extended to include your own extra data, and that's usually a better place to keep the sort of data which might plausibly be passed through to yywrap
. There are other good reasons to chose to build a re-entrant scanner.