Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make the preprocessor insert linebreaks into the macro expansion result? [duplicate]

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?

like image 714
sharptooth Avatar asked Jan 22 '10 09:01

sharptooth


People also ask

What preprocessor macro expands to the current line number in the source file?

__LINE__ is a preprocessor macro that expands to current line number in the source file, as an integer. __LINE__ is useful when generating log statements, error messages intended for programmers, when throwing exceptions, or when writing debugging code.

What does ## mean in preprocessor?

## is Token Pasting Operator. The double-number-sign or "token-pasting" operator (##), which is sometimes called the "merging" operator, is used in both object-like and function-like macros.

What does the '#' symbol do in macro expansion?

The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.

What is ## in macro in C?

Token Pasting / Token Concatenation: It is often useful to merge two tokens into one while expanding macros. This is called token pasting or token concatenation. The '##' preprocessing operator performs token pasting.


2 Answers

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.

like image 67
JaakkoK Avatar answered Oct 10 '22 10:10

JaakkoK


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.

like image 20
hlovdal Avatar answered Oct 10 '22 09:10

hlovdal