7

With C/C++ macros it's quite easy to generated long constructs automatically. For example, if I want a huge set of methods to not ever throw exceptions (a must for COM-exposed methods) I can do something like this:

#define BEGIN_COM_METHOD\
    try{

#define END_COM_METHOD\
    return S_OK;\
    } catch( exception& ) {\
        // set IErrorInfo here\
        return E_FAIL;\
    }

to make such macros manageable one can use "\" character to make the macro definition multiline and more readable.

The problem is sometimes code with such constructs will not compile - something will not expand as expected and invalid code will be present to the compiler. Compiler usually have "generate preprocessed file" option to show the developer the preprocessing result. But in the preprocessed file the macro is expanded into one line and the result is barely readable.

Is it possible to make the preprocessor to keep the linebreaks present in the macro definition?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • 1
    You've found one of the cases where macros should never be used. The obfuscated control flow is particularly nasty here. – Hans Passant Jan 22 '10 at 13:05
  • 2
    @nobugz Yes, but we currently have 16 hundred COM-exposed method and we need a try-catch and parameters tracing in each of them and those bells and whistles must be maintainable. C++ offers no other way of doing that excpt using macros. – sharptooth Jan 25 '10 at 15:43

2 Answers2

6

You can't do it. The replacement text is until the end of the line where it is #defined, so it will not have newlines in it. If your problems with compilation are infrequent, you could run the preprocessed file through indent or something like that before compiling when that happens to help you get more readable code.

JaakkoK
  • 8,247
  • 2
  • 32
  • 50
4

This is not possible since the \ characters are removed in phase 2, before the preprocessor is involved. See the question Poster with the 8 phases of translation in the C language for a list of the phases of translation.

Community
  • 1
  • 1
hlovdal
  • 26,565
  • 10
  • 94
  • 165