When reading the source code of some programs, it is very desirable to be able to find out exactly what header files are included in the source code to determine if it is necessary to manually include # include for special functions. This is achieved through the lexical analysis of Flex, which is essentially a match for regular expressions. Note that this program is not able to handle nested situations (that is, it cannot indicate which files are included in the include file), and the interest can be implemented through the stack. The source code is as follows:
1 /*Source code: IC.L*/2 3 /*define file preprocessing directive file name start State*/4%x IFILE5 6%%7^"#"[\t]*include[\t]*[\"<] {BEGIN IFILE;} /* #include的多种表达方式的正则表达式 * /8<ifile>[^\t\n\">]+ {/* Enter filename status * /9printf"%d:%s\n", Yylineno++,yytext);/*The output line number and file name, Yylineno is the global variable defined by Flex, and Yytext is the currentTen input Stream*/ One { A CharC; - /*possible line breaks at the end of a destination*/ - while((C=input ()) && c!='\ n'); the } - /*revert to initial state*/ - BEGIN INITIAL; -}/*The following re is used to handle line breaks (blank lines) and line breaks, increasing the value of Yylineno*/ +^\n {+ +Yylineno;} -\ n {+ +Yylineno;} +. {/*directly Ignore*/} A%% at - intMainintargcChar*argv[]) - { - /*command line read file name parameter*/ - if(argc<2) - { infprintf (stderr,"usage:%s filename\n", argv[0]); - } toFILE *F; + inti; - /*Looping open files*/ the for(i=1; i<argc;++i) * { $F=fopen (Argv[i],"R"); Panax Notoginseng if(!f) - { the perror (Argv[i]); + exit (exit_failure); A } the /*Start typing again*/ + Yyrestart (f); -yylineno=1; $ /*start a new file, initialize the function to 1*/ $printf"\t%s:\n", Argv[i]); -Yylex ();/*Start Lexical analysis*/ -printf"\ n"); the fclose (f); - }Wuyi return 0; the}
Compile Instructions:
1 $flex-o ic.lex.c ic.l2 $gcc -o ic IC.LEX.C-LFL
Demo Run Results:
1$ ./IC test_inc.c inc_count.lex.c2 TEST_INC.C:3 1: Stdio.h4 5 inc_count.lex.c:6 -: Stdio.h7 +:string. h8 A: Errno.h9 at: Stdlib.hTen +: Inttypes.h One 487: Unistd.h
Visible has achieved the purpose.
Using lexical analysis to realize that the C program contains the header files