Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiline preprocessor macro with trailing comments

I want to define the following ordinary looking macro:

#define MY_ENUM enum MyEnum{ \
    myVal0, \ //Describes this situation
    myVal2  \ //Describes that situation
}

To my surprise this doesn't work due to error: stray ‘\’ in program. Even some whitespace after the backslash results in warning: backslash and newline separated by space. As this answer points out, the backslash must be the last character on the line. This answer points out that line splicing occurs before comments are processed. The reason why this order was chosen makes absolutely no sense to me; the only reason I can imagine this could be done is to allow multiline comments like the following:

//This is a comment which \
follows in the next line

Which looks extremely dangerous as such a thing could just eat up whatever code is on the next line when attempted. The reverse order, i.e replace each comment with single whitespace before splicing lines sounds like a much more sensible choice to me. Can someone explain why this choice was made?

I can work around my original problem with the following:

#define MY_ENUM enum MyEnum{ \
    myVal1, /*Describes this situation*/ \
    myVal2  /*Describes that situation*/ \
}

My purpose when doing this awkward enum macro definition is that this macro must be shared between c++ (where it absolutely must be a class member due to Qt) and c. Defining a macro such as this looks like the only solution to me but the above workaround looks ugly and I absolutely don't want to leave enums uncommented. Am I approaching this problem wrong?

like image 508
Ayberk Özgür Avatar asked Jun 07 '16 16:06

Ayberk Özgür


1 Answers

The problem is that the c-preprocessor just adds another line ending character when the \ is hit and continuated.

Within // comments you can't do that. The \ character isn't accepted to continuate the comment (it's supposed to appear as a single line anyway).


The solution is,- as you found out yourself -, to use the /**/ comment style.

like image 54
πάντα ῥεῖ Avatar answered Oct 19 '22 15:10

πάντα ῥεῖ