Question

What's the meaning of #line in the C language? Where would it be used?

Was it helpful?

Solution

It tells the compiler where the following line actually came from. It's usually only the C preprocessor that adds these, for example, when including a file, it tells the compiler (which is basically only seeing one stream of data) that we're looking at a different file.

This may sound strange, but the preprocessor simply inserts the header files where you specify your includes, and the compiler works on the whole thing (all header files concatenated along with your source code), you can check the result of the preprocessor stage if using gcc with gcc -E myfile.c. In there you'll notice it adds a #line directive whenever you include files, and also whenever it reduces the amount of text fed to the compiler (such as large amounts of comments may be reduced to a single #line directive, skipping ahead)

It is also used by other programs, such as bison/yacc to tell you that the problem (if there's a compile problem) is related to your rules-file at a specific line, which the compiler would otherwise be unable to do, as the bison/yacc generates c-files.

OTHER TIPS

It is called the preprocessor line control directive.

The expansions of both __FILE__ and __LINE__ are altered if a #line directive is used. It causes the compiler to view the line number of the next source line as the specified number.

Its main use is to make the compiler provide more meaningful error messages.

You can find more explanation and a usage example in IBM's documentation.

It is a pragma keyword:

"#line lets you modify the compiler's line number and (optionally) the file name output for errors and warnings. This example shows how to report two warnings associated with line numbers. The #line 200 directive forces the line number to be 200 (although the default is #7) and until the next #line directive, the filename will be reported as "Special". The #line default directive returns the line numbering to its default numbering, which counts the lines that were renumbered by the previous directive."

It allows you to change the apparent line number of the file.

The only use I can think of for it is to make the line numbers sane after a long series of multi-line macros.

usage is:

#line 42

It is mostly used to supply the file names and line numbers of a source file from which a C file (be it header or implementation) was created. Given that, the compiler would emit diagnostics that hint at the source file rather than at the generated file.

Preprocessors also use this to hint at included headers in a preprocessed file that has these expanded.

# is the string injing symbol to the processor c and c++

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top