Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#line - purposes of?

Tags:

c

I unfortunately was doing a little code archeology today (while refactoring out some old dangerous code) and found a little fossil like this:

# line 7 "foo.y"

I was completely flabbergasted to find such an archaic treasure in there. I read up on it on a website for C programming. However it didn't explain WHY anyone would want to use it. I was left to myself therefore to surmise that the programmer put it in purely for the sheer joy of lying to the compiler.

Note: (Mind you the fossil was actually on line 3 of the cpp file) (Oh, and the file was indeed pointing to a .y file that was almost identical to this file.

Does anyone have any idea why such a directive would be needed? Or what it could be used for?

like image 733
C Johnson Avatar asked Aug 07 '10 01:08

C Johnson


2 Answers

It's generally used by automated code generation tools (like yacc or bison) to set the line number to the value of the line in the actual source file rather than the C source file.

That way, when you get an error that says:

a += xyz;
     ^ No such identifier 'xyz' on line 15 of foo.y

you can look at line 15 of the actual source file to see the problem.

Otherwise, it says something ridiculous like No such identifier 'xyz' on line 1723 of foo.c and you have to manually correlate that line in your auto-generated C file with the equivalent in your real file. Trust me, unless you want to get deeply involved in the internals of lexical and semantic analysis (or you want a brain haemorrhage), you don't want to go through the code generated by yacc (bison may generate nicer code, I don't know but nor do I really care since I write the higher level code).

It has two forms as per the C99 standard:

#line 12345
#line 12345 "foo.y"

The first sets just the reported line number, the second changes the reported filename as well, so you can get an error in line 27 of foo.y instead of foo.c.


As to "the programmer put it in purely for the sheer joy of lying to the compiler", no. We may be bent and twisted but we're not usually malevolent :-) That line was put there by yacc or bison itself to do you a favour.

like image 136
paxdiablo Avatar answered Sep 21 '22 12:09

paxdiablo


The only place I've seen this functionality as being useful is for generated code. If you're using a tool that generates the C file from source defined in another form, in a separate file (ie: the ".y" file), using #line can help the user know where the "real" problem is, and where they should go to correct it (the .y file where they put the original code).

like image 28
Reed Copsey Avatar answered Sep 21 '22 12:09

Reed Copsey