Reputation:
I want to replicate some code snippets using the C preprocessor. I know how to handle multi-line macros, but I am facing two difficulties:
I didn't find a way to embed comments in the macro,
The generated output doesn't have newlines.
E.g. here is what I would like to be able to do
#define Snippet \
// This is my snippet \
a= b + c;
(sort of).
Desired generated output:
// This is my snippet
a= b + c;
Do you have solutions for 1. and 2. ? Thanks in advance.
Upvotes: 0
Views: 206
Reputation:
For those interested, I have solved as follows:
The following macro allows to embed C++-style comments:
#define Comment(Text) #/#/ Text
I am adding a reserved character before the end of every line. After macro expansion, I turn it to a newline with a find/replace macro.
#define Snippet \
Comment(This is my snippet)@\
a= b + c;
expands as
// This is my snippet@a= b + c;
and after substitution
// This is my snippet
a= b + c;
I am still looking for a way to have a symbol that would expand as a newline, though the current solution is already manageable.
Upvotes: 0
Reputation: 409196
The problem with the macro as you show it is because of how the compilation process works.
If you look at e.g. this C translation phase reference you will see that line-continuation happens in phase 2, then comments are replaced by space in phase 3, and finally preprocessing happens in phase 4.
That is, after phase 2 what you have is
#define Snippet // This is my snippet a= b+c;
Then after replacing comments in phase 3 the macro definition becomes empty.
The solution for comments is to use block comments using /*
and */
.
There is no solution for the line-continuation problem, as that's how it must work.
Upvotes: 1