Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Preprocessor

The #line directive

Reference for the C #line directive: reset the line number and file name seen by __LINE__, __FILE__ and compiler messages, as used by code generators.

#line changes the line number (and optionally the file name) that the compiler believes it is reading. After #line 100, the next source line counts as line 100, which affects __LINE__, assert messages and compiler diagnostics. Adding a string, #line 100 "parser.y", also changes __FILE__.

It is rarely written by hand. Its job is to let generators (parser generators, template tools, embedded-code preprocessors) make errors point at the original input instead of at the generated C file. The preprocessor itself emits similar line markers (# 12 "file.h") when it includes a file.

C
#line 500 "grammar.y"

Try it

C Resetting the line number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Macros see the changed values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
#line digit-sequence
#line digit-sequence "s-char-sequence"
#line pp-tokens                   /* macro-expanded to one of the above */
Name Description
digit-sequence The line number that the next source line will have. Must be in the range 1 to 2147483647.
"s-char-sequence" Optional new value for __FILE__ and for the file name in diagnostics.

Errors: a zero, non-numeric or out-of-range line number is an error or at least a warning (C99 allows only 1 to 2147483647; zero was accepted by older standards).

Usage notes

  • The number applies to the following line. In the example above, the printf after #line 100 reports 100.
  • Changes persist until the next #line or the end of the file (including after returning from an included file, which restores its own marks).
  • Debuggers and compiler messages follow it. That is the point: an error in a generated file can name the grammar rule that produced it.
  • Do not use it to hide mistakes in hand-written code; it makes stack traces and warnings lie.
  • __LINE__ is an int constant and changes along with #line, as does __FILE__ (a string literal).
  • Compiler-generated markers like # 3 "foo.h" are the same idea in a non-standard spelling. You see them if you run the compiler with -E.
  • Alternative for assertions: __FILE__ and __LINE__ are usually all you need in a logging macro; leave #line to tools.