Using the line...file directive

Viewed 65

What is an example usage of why someone would want to reset/change the current line number or filename in a program using the #line directive, for example:

#line 10000 "somefile.c"
printf("File: %s, Line: %d", __FILE__, __LINE__)

What would be an example of how that could be useful?

1 Answers

The directive is used by programs that generate C code automatically, as flex(1) or yacc(1), to indicate where in the original source file was the code inserted.

Imagine that you make a grammar specification for yacc(1) in a file that at some point inserts into the source file it generates (yy.tab.c) the source code you provided to it to be substituted literally. Yacc introduces references to it's source code, so you can go back to the original .y file and see the code you wrote

If you look at the C source file created by yacc, you will find directives like

#line 357 "myfile.y"
... /* your inserted code */
#line 20547 "yy.tab.c"
... /* more yacc generated code */
#line 380 "myfile.y"
... /* more literal code written by you */
#line 21250 "yy.tab.c"
...

so the debugger will insert the proper references to the real source file, and not to the yacc processed intermediate C source.

The cpp preprocessor indicates each change of file, by inserting a #line 1 "stdio.h" at the beginning of an #include <stdio.h> expansion, and a #line 37 "my_original_source.c" on returning back from the #include to include in the debugger info the proper lines in the source code. You can see this happening if you just preprocess a source code:

cpp mysourcefile.c | more

and you will see a pair of #line directives on include entry and include exit points, reseting the line counter.

Related