tags:

views:

79

answers:

1

I am generating C code based on information provided by another file (an XML file). Certain chunks of C are included in this XML file and should be included verbatim in my generated C file. I wish to use the #line directive, so that if these chunks contain an error, the user will see the line number in the XML file that the chunk came from. For example, I wish to generate code like:

int main() {
   #line 35 "file.xml"
   ....
   #line
}

I wish to somehow "close" the #line section, I mean I think if there is an error e.g. with the closing } and that is generated by my program, the user should not see "error on line 36 of file.xml", that will be meaningless to them and confuse them.

For example, I could imagine a #line directive on its own (as in my example) would do something like that. But it doesn't work, and there is no such mention of any such facility in the gcc docs on #line.

Is there any such facility I'm missing? Or am I just asking for something that doesn't exist? How would you go about such a problem?

+3  A: 

You need to issue another #line directive "resetting" to the line and filename of your original file.

Roger Pate
Thanks for your answer! I was thinking about that too. But that would require me to know the line-number I'm up to in the file I am generating. Possible, but surely, I'm thinking, the C compiler already has the logic built-in to output errors against lines in the actual C file, as that's what it'd do if there had never been any #line directives in the file at all. There's no point me duplicating things already built into the compiler (unless I have to?). Plus, I am just writing the generated C file to a stream, so it's not totally trivial to work out the current line number.
Adrian Smith
No - the C pre-processor doesn't provide that mechanism. Computers are good at counting; make it (the code generator) do the work for you.
Jonathan Leffler
The C preprocessor can do that for you---if you use an `#include` directive. (Look at preprocessed output to see all the #line directives generated.)
Roger Pate