Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lex rule for C preprocessor directive

I am writing a lex program to tokenize a C program. I've written the following rule to match a C preprocessor directive

 #.*                             {printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);}

But when I use a file as an input to yyin, pre-processor directives in the file are matched by yytext displayed is empty

e.g I get

is a PREPROCESSOR DIRECTIVE

There is no problem when yyin is stdin but this arises only when a file is input. Is there an alternate LEX rule?

like image 492
Sridhar Avatar asked Jun 01 '26 08:06

Sridhar


1 Answers

Focus on the fact that it doesn't work with a file instead of the lex specification, because that is more likely to cause the problem. The printf in the lex file should always at least print the #. The following does work with a file:

%{
#include <stdio.h>
%}
%%
#.* { printf("'%s' preproc\n", yytext); }
%%

int yywrap(void)
{
        return 1;
}

int main(int argc, char ** argv)
{
        if (argc > 1)
        {
                if ((yyin = fopen(argv[1], "r")) == NULL)
                {
                        fprintf(stderr, "Can't open `%s'.\n", argv[1]);
                        exit(1);
                }
        }
        return (yylex());
}
like image 113
Bryan Olivier Avatar answered Jun 03 '26 22:06

Bryan Olivier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!