Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#line keyword in C

Tags:

c

line

I am trying to understand some code and I've come across a keyword that I've never seen before. I tried to google it, but haven't found anything regarding it as well.

char *valtext;
#line 1 "Values.l"
#define INITIAL 0
#line 2 "Values.l"
int reserve(char *s);
#line 388 "lex.val.c"

I've included the entire block hoping that perhaps someone can help me understand this chunk of code. I can't find any files on my system named "Values.l" and this chunk of code is located in the "lex.val.c" file.

Thanks in advance.

like image 597
Seb Avatar asked Aug 18 '11 14:08

Seb


2 Answers

A #line directive sets the compiler's setting for the current file name and line number. This affects the __FILE__ and __LINE__ symbols, the output generated by a failing assert(), and diagnostic messages (errors and warnings). It's typically used by the preprocessor so that error and warning messages can refer to the original source code, not to the output of the preprocessor (which is typically discarded by the time you see any messages).

It's also used by other tools that generate C source code, such as lex/flex and yacc/bison, so that error messages can refer to the input file rather than the (temporary) generated C code.

The definitive reference is the C standard (pdf), section 6.10.4.

A line of the form

#line number

sets the current line number. A line of the form

#line number "file-name"

sets both the line number and the file name. You can also generate one of these two forms via macro expansion; for example:

#define LINE 42
#define FILE "foo.c"
#line LINE FILE
like image 131
Keith Thompson Avatar answered Sep 23 '22 13:09

Keith Thompson


The #line directive is for the use of preprocessors, so that the original line number of the source can be communicated to the C compiler. It makes it so that error messages from the compiler properly refer to line numbers the user will understand.

For example, line 12 of your mycode.c may go through a preprocessor, and now be line 183 of mycode.tmp.cc. If the C compiler finds an error on that line, you don't want to be told the error is on line 183 of mycode.tmp.cc. So the C compiler needs to be given "original coordinates" of each line. The #line directive does this, telling the compiler the current line number and filename to use in error messages.

like image 42
Ned Batchelder Avatar answered Sep 22 '22 13:09

Ned Batchelder