Home > OS >  Does C preprocessed file contain source file line number information?
Does C preprocessed file contain source file line number information?

Time:05-26

Here is the problem:
I have a C source file main.c and the corresponding preprocessed file main.i. Given a line in main.i, how can I get the corresponding line number in main.c?

CodePudding user response:

The C standard does not specify this. GCC and Clang emit lines starting with # followed by a space, a line number, a file name, and other information.. You can determine the line number in main.c:

  • Read the preprocessed file, main.i. After any line with # followed by a space, a number, and a file name that is not “main.c”, read and ignore further lines until there is a # followed by a space, a number, and “main.c”. Remember that number as the current line number.
  • Subsequent lines until another # line in this form are lines from main.c (after preprocessing) with consecutive line numbers continuing from the line number remembered above.

CodePudding user response:

When used as a separate phase producing a text file, the C preprocessor usually inserts #line directives, sometimes appearing as bare # directives providing the original file name, line number and other contextual information. #line directives have this form:

# line pp-tokens new-line

which after macro substitution should become:

# line digit-sequence new-line

or

# line digit-sequence " s-char-sequenceopt " new-line

Where digit-sequence is the line number of the next list in the source stream and the s-char-sequenceopt is the name of the file to use for diagnostics and as a replacement for the __FILE__ macro. Subsequent newlines increment the line number thus defined.

#line directives are produced by external programs that generate C code files to make compiler diagnostics point to the original source file.

C Compilers such as gcc and clang produce similar information in their preprocessing output in the form:

# number filename other-information new-line

This syntax is not defined by the C Standard but very common in preprocessing output produced by C compilers. The C standard does not define this output, used mostly for debugging purposes.

  •  Tags:  
  • c
  • Related