%{ #include #define MAX_INCLUDE_DEPTH 10 YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH]; int include_stack_pos = 0; FILE *tmp_file_ptr = NULL; %} %option main %option yywrap %x INCL %% ^"#include"[ \t]+ BEGIN(INCL); .|\n ECHO; .*\n { if(include_stack_pos >= MAX_INCLUDE_DEPTH) { fprintf(stderr,"Includes nested too deeply!\n"); exit(1); } include_stack[include_stack_pos++] = YY_CURRENT_BUFFER; yytext[strlen(yytext)-1] = '\0'; /* remove '\n' */ if(!(tmp_file_ptr = fopen(yytext, "r"))) { fprintf(stderr, "Cannot open include file '%s'!\n", yytext); exit(1); } yy_switch_to_buffer( yy_create_buffer(tmp_file_ptr, YY_BUF_SIZE)); BEGIN(INITIAL); } %% int yywrap() { if(--include_stack_pos < 0) return 1; else { yy_delete_buffer(YY_CURRENT_BUFFER); yy_switch_to_buffer( include_stack[include_stack_pos]); return 0; } }