7.6 Line Control

The #line directive changes the compiler's internally stored line number and filename to a given line number and filename. The compiler uses the line number and filename to refer to errors that it finds during compilation. The line number usually refers to the current input line, and the filename refers to the current input file. The line number is incremented after each line is processed. The syntax is

Syntax

control-line :
#line digit-sequence new-line
#line digit-sequence "filename" opt new-line
#line digit-sequence preprocessing-tokens new-line

The digit-sequence value in the #line directive can be any integer constant in the range 1 through 32,767. The filename can be any combination of characters and must be enclosed in double quotation marks (“ ”). If filename is omitted, the previous filename remains unchanged. In the third line of syntax above, macro replacement is performed on the preprocessing tokens and the result must match one of the two previous lines.

You can alter the source line number and filename by writing a #line directive. The translator uses the line number and filename to determine the values of the predefined macros __FILE__ and __LINE__.

The current line number and filename are always available through the predefined macros __LINE__ and __FILE__. You can use the __LINE__ and __FILE__ identifiers to insert self-descriptive error messages into the program text.

The __FILE__ macro expands to a string whose contents are the filename, surrounded by double quotation marks (" "). See “Predefined Macros”.

If you change the line number and filename, the compiler ignores the previous values and continues processing with the new values. The #line directive is typically used by program generators to cause error messages to refer to the original source file instead of to the generated program.

These examples illustrate #line and the __LINE__ and __FILE__ macros.

#line 151 "copy.c"

In this statement, the internally stored line number is set to 151 and the filename is changed to copy.c.

#define ASSERT(cond)

if( !(cond) )\

{printf( "assertion error line %d, file(%s)\n", \

__LINE__, __FILE__ );}

In this example, the macro ASSERT uses the predefined identifiers __LINE__ and __FILE__ to print an error message about the source file if a given “assertion” is not true.