Precise Control for Debugging and Code Generation
python
number
β the new line number the compiler should treat as the current line.
"file_name"
β an optional logical file name that will appear in compiler messages and the FILE macro.
python
This means: "The next physical line of code will be treated by the compiler as line number 4."
main
#include <stdio.h> #line 100 "template.dsl" void create_label() { int a = "oops"; // error } int main() { create_label(); return 0; }
Why this is useful
The #line
directive changes how the compiler sees the location of the code β that is, which file and line it appears to be in. This does not affect how the program executes.
This is useful for code generation tools, improving clarity of error messages or mapping between generated code and templates or DSLs.
If you suspect that a certain function might behave incorrectly, you can place the following before it:
python
And if an error does occur, the compiler will report:
python
In other words, you have "tricked" the compiler into thinking that this part of the code comes from a different source.
How long does it last?
The effect of #line
applies to all subsequent code, up until the end of the file or the next #line
directive.
If you want to "fool" the compiler for just a few lines β you can insert another #line
afterward to switch back to the original location.
main
#include <stdio.h> #line 4 "fileWithFuncs.c" void func() { printf("%s:%d\n", __FILE__, __LINE__); // fileWithFuncs.c:5 } #line 9 "main.c" int main() { func(); return 0; }
So, to limit the effect of #line
, just set a new location β either back to the real one or to something else.
Swipe to start coding
Imagine you're building a code generator for a GUI, which converts simple text-based templates into C functions.
When something goes wrong in a generated function, you want the compiler to report the error as if it happened in the original template file, not in the generated .c
file.
To achieve this, you decide to use the #line
directive.
- Fill in the first
___
so that the compiler believes the functioncreate_button()
starts at line 15 in the filebuttons.ui
. - Fill in the second
___
to return the context tomain.c
, starting at line 20.
Thanks for your feedback!